Jest's globalSetup make my tests to not being recognized - node.js

So I was following this example to make a test with mongodb on jest, but after configuring everything I just get this when running jest:
If I remove globalSetup from jest.config.js, the tests appear although with errors because of mongo-enviroment and teardown configs been dependents on globalSetup:
If I run jest --debug I get this:
{
"configs": [
{
"automock": false,
"browser": false,
"cache": true,
"cacheDirectory": "/tmp/jest_rs",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"detectLeaks": false,
"detectOpenHandles": false,
"errorOnDeprecated": false,
"filter": null,
"forceCoverageMatch": [],
"globals": {},
"haste": {
"providesModuleNodeModules": []
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"js",
"json",
"jsx",
"node"
],
"moduleNameMapper": {},
"modulePathIgnorePatterns": [],
"name": "9f5155d702743ad8d949d6d219c1bc22",
"prettierPath": null,
"resetMocks": false,
"resetModules": false,
"resolver": null,
"restoreMocks": false,
"rootDir": "/home/mauricio/work/growthbond/gbnd1",
"roots": [
"/home/mauricio/work/growthbond/gbnd1"
],
"runner": "jest-runner",
"setupFiles": [
"/home/mauricio/work/growthbond/gbnd1/node_modules/regenerator-runtime/runtime.js"
],
"setupTestFrameworkScriptFile": "/home/mauricio/work/growthbond/gbnd1/testConfig/setupScript.js",
"skipFilter": false,
"snapshotSerializers": [],
"testEnvironment": "/home/mauricio/work/growthbond/gbnd1/testConfig/mongo-environment.js",
"testEnvironmentOptions": {},
"testLocationInResults": false,
"testMatch": [
"**/__tests__/**/*.js?(x)",
"**/?(*.)+(spec|test).js?(x)"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testRegex": "",
"testRunner": "/home/mauricio/work/growthbond/gbnd1/node_modules/jest-jasmine2/build/index.js",
"testURL": "http://localhost",
"timers": "real",
"transform": [
[
"^.+\\.jsx?$",
"/home/mauricio/work/growthbond/gbnd1/node_modules/babel-jest/build/index.js"
]
],
"transformIgnorePatterns": [
"/node_modules/"
],
"watchPathIgnorePatterns": []
}
],
"globalConfig": {
"bail": false,
"changedFilesWithAncestor": false,
"collectCoverage": false,
"collectCoverageFrom": null,
"coverageDirectory": "/home/mauricio/work/growthbond/gbnd1/coverage",
"coverageReporters": [
"json",
"text",
"lcov",
"clover"
],
"coverageThreshold": null,
"detectLeaks": false,
"detectOpenHandles": false,
"errorOnDeprecated": false,
"expand": false,
"filter": null,
"globalSetup": "/home/mauricio/work/growthbond/gbnd1/testConfig/setup.js",
"globalTeardown": "/home/mauricio/work/growthbond/gbnd1/testConfig/teardown.js",
"listTests": false,
"maxWorkers": 3,
"noStackTrace": false,
"nonFlagArgs": [],
"notify": false,
"notifyMode": "always",
"passWithNoTests": false,
"projects": null,
"rootDir": "/home/mauricio/work/growthbond/gbnd1",
"runTestsByPath": false,
"skipFilter": false,
"testFailureExitCode": 1,
"testPathPattern": "",
"testResultsProcessor": null,
"updateSnapshot": "new",
"useStderr": false,
"verbose": true,
"watch": false,
"watchman": true
},
"version": "23.6.0"
}
Note that
"testMatch": [
"**/__tests__/**/*.js?(x)",
"**/?(*.)+(spec|test).js?(x)"
],
looks perfectly fine.
Related files
jest.config.js:
module.exports = {
globalSetup: './testConfig/setup.js',
globalTeardown: './testConfig/teardown.js',
testEnvironment: './testConfig/mongo-environment.js',
setupTestFrameworkScriptFile: './testConfig/setupScript.js',
verbose: true
}
setup.js (globalSetup):
const path = require('path');
const fs = require('fs');
const MongodbMemoryServer = require('mongodb-memory-server');
const globalConfigPath = path.join(__dirname, 'globalConfig.json');
const mongod = new MongodbMemoryServer.default({
instance: {
dbName: 'jest'
},
binary: {
version: '3.2.18'
},
autoStart: false,
});
module.exports = async () => {
if (!mongod.isRunning) {
await mongod.start();
}
const mongoConfig = {
mongoDBName: 'jest',
mongoUri: await mongod.getConnectionString()
};
// Write global config to disk because all tests run in different contexts.
fs.writeFileSync(globalConfigPath, JSON.stringify(mongoConfig));
console.log('Config is written');
// Set reference to mongod in order to close the server during teardown.
global.__MONGOD__ = mongod;
process.env.MONGO_URL = mongoConfig.mongoUri;
};
teardown.js:
module.exports = async function() {
await global.__MONGOD__.stop();
};
mongo-environment.js:
const NodeEnvironment = require('jest-environment-node');
const path = require('path');
const fs = require('fs');
const globalConfigPath = path.join(__dirname, 'globalConfig.json');
module.exports = class MongoEnvironment extends NodeEnvironment {
constructor(config) {
super(config);
}
async setup() {
console.log('Setup MongoDB Test Environment');
const globalConfig = JSON.parse(fs.readFileSync(globalConfigPath, 'utf-8'));
this.global.__MONGO_URI__ = globalConfig.mongoUri;
this.global.__MONGO_DB_NAME__ = globalConfig.mongoDBName;
await super.setup();
}
async teardown() {
console.log('Teardown MongoDB Test Environment');
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
};
user.test.js (mongodb related test):
const MongoClient= require('mongodb');
const User = require('../../db/models/user');
let connection;
let db;
beforeAll(async () => {
connection = await MongoClient.connect(global.__MONGO_URI__);
db = await connection.db(global.__MONGO_DB_NAME__);
});
afterAll(async () => {
await connection.close();
await db.close();
});
describe('Password Encription', async () => {
const uEmail = 'test#a.com';
const uPass = '123test';
var testUser = new User({
email:uEmail ,
password: uPass
});
await testUser.save()
test('Encripted password string is different to plain password', async () => {
user = await User.findOne({ email: uEmail });
expect(user.password).not.toEqual(uPass);
});
test('ComparePassword method verify that plain password is the same that encrypted password', async () => {
rightPassword = await user.comparePassword(uPass);
expect(rightPassword).toBeTrue();
});
test('ComparePassword method verify that altered plain password is not the same that encrypted password', async () => {
wrongPassword = await user.comparePassword(uPass+'random');
expect(rightPassword).not.toBeTrue();
});
});
authService.test.js:
require('dotenv').config()
const authS = require('../../services/authService');
const jwt = require('jsonwebtoken');
describe('Auth Services',()=>{
const payload = {test:'This is a test'}
const user = {id:101}
const mockSecret = 'SECRET123HAAJAHJSoafdafda'
const token = authS.jwtSign(user,payload)
test('JWT sign', () => {
expect(authS.jwtSign(user,payload)).toBeString();
});
test('JWT verify different secret', ()=>{
badToken = jwt.sign(
payload,
mockSecret,
{ subject:String(user.id),
expiresIn:'1h'
}
);
expect(()=>authS.jwtVerify(badToken)).toThrowError(jwt.JsonWebTokenError)
})
test('JWT verify payload', ()=>{
expect(authS.jwtVerify(authS.jwtSign(user,payload))).toMatchObject(payload)
})
})
My environment:
node v11.0.0
jest 23.6.0
As a matter of fact I know that my test non mongodb related run if I comment
globalSetup: './testConfig/setup.js',
globalTeardown: './testConfig/teardown.js',
testEnvironment: './testConfig/mongo-environment.js',
from jest.config.js :

My problem was that I had another GlobalSetup file and they were conflicting. In my custom GlobalSetup I imported the #Shelf/jest-mongodb/setup and add it to mine.
const jestMongoSetup = require("#shelf/jest-mongodb/setup")
module.exports = async () => {
process.env.TZ = "UTC" //My config
await jestMongoSetup()
}

Related

Trouble connecting express api to nuxt app and mongodb

It's been seriously 10 days since i'm trying to deploy my web app online. i've gone back and forth between heroku and digital ocean. nothing solved. i've asked questions here all i get is a long post with technical terms i' not able to understand. Here's my problem :
i have a nuxt app with express.js in the backend and mongodb as the database. At first i had trouble with configuring host and port for my nuxt app. once i fixed it, anoither problem appeared : i'm not receiving data from the database. i don't if it's something related to database connection or with the express api configuration.
here's my nuxt config
export default {
ssr: false,
head: {
titleTemplate: 'Lokazz',
title: 'Lokazz',
meta: [
{ charset: 'utf-8' },
{
name: 'viewport',
content: 'width=device-width, initial-scale=1'
},
{
hid: 'description',
name: 'description',
content:
'Lokazz'
}
],
link: [
{
rel: 'stylesheet',
href:
'https://fonts.googleapis.com/css?family=Work+Sans:300,400,500,600,700&subset=latin-ext'
}
]
},
css: [
'swiper/dist/css/swiper.css',
'~/static/fonts/Linearicons/Font/demo-files/demo.css',
'~/static/fonts/font-awesome/css/font-awesome.css',
'~/static/css/bootstrap.min.css',
'~/assets/scss/style.scss'
],
plugins: [
{ src: '~plugins/vueliate.js', ssr: false },
{ src: '~/plugins/swiper-plugin.js', ssr: false },
{ src: '~/plugins/vue-notification.js', ssr: false },
{ src: '~/plugins/axios.js'},
{ src: '~/plugins/lazyLoad.js', ssr: false },
{ src: '~/plugins/mask.js', ssr: false },
{ src: '~/plugins/toastr.js', ssr: false },
],
buildModules: [
'#nuxtjs/vuetify',
'#nuxtjs/style-resources',
'cookie-universal-nuxt'
],
styleResources: {
scss: './assets/scss/env.scss'
},
modules: ['#nuxtjs/axios', 'nuxt-i18n','vue-sweetalert2/nuxt', '#nuxtjs/auth-next', "bootstrap-vue/nuxt"],
bootstrapVue: {
bootstrapCSS: false, // here you can disable automatic bootstrapCSS in case you are loading it yourself using sass
bootstrapVueCSS: false, // CSS that is specific to bootstrapVue components can also be disabled. That way you won't load css for modules that you don't use
},
i18n: {
locales: [
{ code: 'en', file: 'en.json' },
],
strategy: 'no_prefix',
fallbackLocale: 'en',
lazy: true,
defaultLocale: 'en',
langDir: 'lang/locales/'
},
router: {
linkActiveClass: '',
linkExactActiveClass: 'active',
},
server: {
port: 8080, // default: 3000
host: '0.0.0.0' // default: localhost
},
auth: {
strategies: {
local: {
token: {
property: "token",
global: true,
},
redirect: {
"login": "/account/login",
"logout": "/",
"home": "/page/ajouter-produit",
"callback": false
},
endpoints: {
login: { url: "/login", method: "post" },
logout: false, // we don't have an endpoint for our logout in our API and we just remove the token from localstorage
user:false
}
}
}
},
};
here's my package.json
{
"name": "martfury_vue",
"version": "1.3.0",
"description": "Martfury - Multi-purpose Ecomerce template with vuejs",
"author": "nouthemes",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"config": {
"nuxt": {
"host": "0.0.0.0",
"port": "8080"
}
},
}
here's my repository.js file
import Cookies from 'js-cookie';
import axios from 'axios';
const token = Cookies.get('id_token');
const baseDomain = 'https://lokazzfullapp-8t7ec.ondigitalocean.app';
export const customHeaders = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
export const baseUrl = `${baseDomain}`;
export default axios.create({
baseUrl,
headers: customHeaders
});
export const serializeQuery = query => {
return Object.keys(query)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
.join('&');
};
an example of an api call i make locally that works without a problem :
import Repository, { serializeQuery } from '~/repositories/Repository.js';
import { baseUrl } from '~/repositories/Repository';
import axios from 'axios'
const url = baseUrl;
export const actions = {
async getProducts({ commit }, payload) {
const reponse = await axios.get(url)
.then(response => {
commit('setProducts', response.data);
return response.data;
})
.catch(error => ({ error: JSON.stringify(error) }));
return reponse;
},
}
here's my index.js (express file)
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose')
const cors = require('cors');
//const url = 'mongodb://localhost:27017/lokazz'
const url = 'mongodb+srv://lokazz:zaki123456#cluster0.hsd8d.mongodb.net/lokazz?retryWrites=true&w=majority'
const jwt = require('jsonwebtoken')
const con = mongoose.connection
mongoose.connect(url, {useNewUrlParser:true}).then(()=>{
const app = express();
// middlleware
app.use(express.json())
app.use(cors());
//products routes
const products = require('./product/product.router');
app.use('/', products)
//users routes
const users = require('./user/user.router');
app.use('/', users)
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
}).catch(error => console.log(error.reason));
con.on('open', () => {
console.log('connected...')
})
My directory structure
the error i get after the api request, meaning it's not receving any data.
ebd1ecd.js:2 TypeError: Cannot read properties of undefined (reading 'username')
at f.<anonymous> (c88240c.js:1)
at f.t._render (ebd1ecd.js:2)
at f.r (ebd1ecd.js:2)
at wn.get (ebd1ecd.js:2)
at new wn (ebd1ecd.js:2)
at t (ebd1ecd.js:2)
at f.In.$mount (ebd1ecd.js:2)
at init (ebd1ecd.js:2)
at ebd1ecd.js:2
at v (ebd1ecd.js:2)
idk if it's a problem with mongodb connection cluster or the api call.

node-loader not handling node_modules file

When running
npm run electron:serve
I get this error:
in ./node_modules/msnodesqlv8/build/Release/sqlserverv8.node
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
I think I understand the error. My webpack doesn't know how to handle the .node file in this dependency ("msnodesqlv8": "^2.2.0")
I have tried adding node-loader but I've not had any success with it. I have tried configuring it in my vue.config.js like this:
module.exports = {
transpileDependencies: [
'vuetify'
],
configureWebpack: {
devtool: 'source-map'
},
pluginOptions: {
electronBuilder: {
preload: 'preload/preload.js',
"directories": {
"buildResources": "build"
},
mainProcessWatch:['src/services/background/**'],
"files": [
"build/**/*",
"!node_modules"
],
"win": {
"asar": false,
"target": "nsis",
"icon": "build/icon.ico"
},
"nsis": {
"installerIcon": "build/icon.ico",
"installerHeaderIcon": "build/icon.ico",
"deleteAppDataOnUninstall": true
}
}
},
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = "Configuration Utility";
return args;
});
config.module
.rule('node')
.test(/\.node$/)
.use('node-loader')
.loader('node-loader')
.end();
config.module
.rule('pug')
.test(/\.pug$/)
.use('pug-plain-loader')
.loader('pug-plain-loader')
.end();
}
}
I also tried adding a separate webpack.config.js with no success:
module.exports = {
target: "node",
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.node$/,
loader: "node-loader",
},
],
},
};
How can I get this working?
You need to move the node loader into the chainWebpack of the electron builder for this to work.
module.exports = {
transpileDependencies: [
'vuetify'
],
configureWebpack: {
devtool: 'source-map'
},
pluginOptions: {
electronBuilder: {
preload: 'preload/preload.js',
"directories": {
"buildResources": "build"
},
// THESE NEXT 3 LINES HERE:
chainWebpackMainProcess: config => {
config.module.rule('node').test(/\.node$/).use('node-loader').loader('node-loader').end()
},
mainProcessWatch:['src/services/background/**'],
"files": [
"build/**/*",
"!node_modules"
],
"win": {
"asar": false,
"target": "nsis",
"icon": "build/icon.ico"
},
"nsis": {
"installerIcon": "build/icon.ico",
"installerHeaderIcon": "build/icon.ico",
"deleteAppDataOnUninstall": true
}
}
},
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = "Configuration Utility";
return args;
});
config.module
.rule('pug')
.test(/\.pug$/)
.use('pug-plain-loader')
.loader('pug-plain-loader')
.end();
}
}

Uncaught TypeError: Cannot read property 'split' of undefined (Webpack)

I'm making an update to a Chrome Extension (using Create React App) of mine, but suddenly I get this error:
Uncaught TypeError: Cannot read property 'split' of undefined
For the following code:
/* WEBPACK VAR INJECTION */(function(process) {
Object.defineProperty(exports, "__esModule", { value: true });
const defer_to_connect_1 = __webpack_require__(1533);
const nodejsMajorVersion = Number(process.versions.node.split('.')[0]);
The error occurs in the last line for (process.versions.node.split('.')[0] and the code is generated by Webpack.
Here is my Webpack Config:
"use strict";
const autoprefixer = require("autoprefixer");
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ManifestPlugin = require("webpack-manifest-plugin");
const InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin");
const SWPrecacheWebpackPlugin = require("sw-precache-webpack-plugin");
const eslintFormatter = require("react-dev-utils/eslintFormatter");
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const paths = require("./paths");
const getClientEnvironment = require("./env");
const publicPath = paths.servedPath;
const shouldUseRelativeAssetPaths = publicPath === "./";
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== "false";
const publicUrl = publicPath.slice(0, -1);
const env = getClientEnvironment(publicUrl);
if (env.stringified["process.env"].NODE_ENV !== '"production"') {
throw new Error("Production builds must have NODE_ENV=production.");
}
const cssFilename = "static/css/[name].css";
const extractTextPluginOptions = shouldUseRelativeAssetPaths
? { publicPath: Array(cssFilename.split("/").length).join("../") }
: {};
module.exports = {
mode: "production",
externals: ["dns"],
bail: true,
devtool: shouldUseSourceMap ? "inline-source-map" : false,
entry: {
app: [require.resolve("./polyfills"), paths.appIndexJs],
content: [require.resolve("./polyfills"), "./src/content.js"],
},
optimization: {
minimize: false,
},
output: {
path: paths.appBuild,
filename: "static/js/[name].js",
chunkFilename: "static/js/[name].[chunkhash:8].chunk.js",
publicPath: publicPath,
devtoolModuleFilenameTemplate: (info) =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, "/"),
},
resolve: {
modules: ["node_modules", paths.appNodeModules].concat(
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"],
alias: {
"react-native": "react-native-web",
},
plugins: [new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])],
},
module: {
strictExportPresence: true,
rules: [
{
test: /\.(js|jsx|mjs)$/,
enforce: "pre",
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve("eslint"),
},
loader: require.resolve("eslint-loader"),
},
],
include: paths.appSrc,
},
{
oneOf: [
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve("url-loader"),
options: {
limit: 10000,
name: "static/media/[name].[hash:8].[ext]",
},
},
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve("babel-loader"),
options: {
compact: true,
},
},
{
test: /\.css$/,
use: [{ loader: MiniCssExtractPlugin.loader }, "css-loader"],
},
{
loader: require.resolve("file-loader"),
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
options: {
name: "static/media/[name].[hash:8].[ext]",
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
new webpack.DefinePlugin(env.stringified),
new MiniCssExtractPlugin({
filename: cssFilename,
}),
new ManifestPlugin({
fileName: "asset-manifest.json",
}),
new SWPrecacheWebpackPlugin({
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: "service-worker.js",
logger(message) {
if (message.indexOf("Total precache size is") === 0) {
return;
}
if (message.indexOf("Skipping static resource") === 0) {
return;
}
console.log(message);
},
minify: true,
navigateFallback: publicUrl + "/index.html",
navigateFallbackWhitelist: [/^(?!\/__).*/],
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
node: {
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty",
child_process: "empty",
},
};
I've already tried updating the dependencies, but with little success. What could be the problem?

global is not defined in jest test file

global variable in JS is not able to access in jest test files, also not able to change the values which are already defined in global.
the work around I have did is as follow:
require('./../../../../bin/global');
describe('gloablAccessMethod', () => {
beforeEach(() => {
// jest.spyOn(regionConfig,'global.regionConfig').mockImplementation(() => ({
// 'ENABLE_CONFIG' : false
// }));
global.regionConfig.ENABLE_CONFIG = false;
});
const PHONE_PREFIX_SG = 65;
it('should access mock global variables', () =>{
//some sample tests
});
});
jest configuration
"jest": {
"timers": "fake",
"testEnvironment": "node",
"setupFiles": [
"./.jest/setEnv.js"
],
"setupFilesAfterEnv": [
"./.jest/setup.js"
],
"coverageReporters": [
"text",
"cobertura"
],
"collectCoverage": true,
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
]
},```

Jest hangs when Svelte configuration includes svelte-preprocess

The Snowpack Svelte template includes a Jest setup which works well for Svelte apps and works out of the box. However, once svelte-preprocess is added, Jest hangs indefinitely.
This can easily be seen using https://github.com/agneym/svelte-tailwind-snowpack, which can be setup with:
npx create-snowpack-app dir-name --template svelte-tailwind-snowpack
svelte.config.js looks like this, although even if the pre-processor doesn't include Tailwind it still hangs:
const sveltePreprocess = require("svelte-preprocess");
const preprocess = sveltePreprocess({
postcss: {
plugins: [require("tailwindcss"), require("autoprefixer")],
},
});
module.exports = {
preprocess,
};
jest.config.js
const fs = require("fs");
const path = require("path");
// Use this instead of `paths.testsSetup` to avoid putting
// an absolute filename into configuration after ejecting.
// const setupTestsFile = fs.existsSync(paths.testsSetup)
// ? `<rootDir>/src/setupTests.js`
// : undefined;
const setupTestsFile = true;
module.exports = function () {
const userSvelteConfig = getUserSvelteConfig();
return {
testMatch: [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}",
],
transform: {
"^.+\\.svelte$": [
"jest-transform-svelte",
{ preprocess: userSvelteConfig.preprocess },
],
"^.+\\.(js|ts)$": path.resolve(__dirname, "jest/babelTransform.js"),
},
moduleFileExtensions: ["js", "ts", "svelte"],
testPathIgnorePatterns: ["node_modules"],
transformIgnorePatterns: ["node_modules"],
bail: false,
verbose: true,
setupFilesAfterEnv: setupTestsFile ? ["<rootDir>/jest.setup.js"] : [],
};
};
function getUserSvelteConfig() {
const userSvelteConfigLoc = path.join(process.cwd(), "svelte.config.js");
if (fs.existsSync(userSvelteConfigLoc)) {
return require(userSvelteConfigLoc);
}
return {};
}
Have to eject the default Snowpack configuration file and use svelte-jester instead of the config they were using. The config below works:
const fs = require("fs");
const path = require("path");
// Use this instead of `paths.testsSetup` to avoid putting
// an absolute filename into configuration after ejecting.
// const setupTestsFile = fs.existsSync(paths.testsSetup)
// ? `<rootDir>/src/setupTests.js`
// : undefined;
const setupTestsFile = true;
module.exports = function () {
const userSvelteConfig = getUserSvelteConfig();
return {
rootDir: "./",
testMatch: [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}",
],
transform: {
"^.+\\.svelte$": [
"svelte-jester",
{ "preprocess": true },
],
"^.+\\.(js|ts)$": "babel-jest",
},
moduleFileExtensions: ["js", "ts", "svelte"],
testPathIgnorePatterns: ["node_modules"],
transformIgnorePatterns: ["node_modules"],
bail: false,
verbose: true,
setupFilesAfterEnv: setupTestsFile ? ["<rootDir>/jest.setup.js"] : [],
};
};
function getUserSvelteConfig() {
const userSvelteConfigLoc = path.join(process.cwd(), "svelte.config.js");
if (fs.existsSync(userSvelteConfigLoc)) {
return require(userSvelteConfigLoc);
}
return {};
}

Resources