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 {};
}
Related
I'm trying to build my project using webpack. this is my webpack configuration file.
import * as path from 'path';
import * as webpack from 'webpack';
import { fileURLToPath } from 'url';
import nodeExternals from 'webpack-node-externals';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const input = path.resolve(__dirname, '../src/server');
const output = path.resolve(__dirname, '../server');
const config: webpack.Configuration = {
entry: {
server: path.resolve(input, './index.ts'),
},
experiments: {
outputModule: true,
},
externals: [
nodeExternals(),
],
module: {
rules: [
{
exclude: /node_modules/,
loader: 'ts-loader',
options: {
transpileOnly: true,
},
test: /\.ts(x?)$/,
},
],
},
name: 'server',
output: {
filename: '[name].js',
path: output,
publicPath: '/node/',
chunkFormat: 'module',
},
resolve: {
extensions: ['*', '.js', '.jsx', '.json', '.ts', '.tsx'],
},
target: 'node',
};
export default config;
when I run bundle, I get an error.
module.exports = require("express"); ^
ReferenceError: require is not defined in ES module scope, you can use
import instead This file is being treated as an ES module because it
has a '.js' file extension and
'/test/package.json' contains "type":
"module". To treat it as a CommonJS script, rename it to use the
'.cjs' file extension.
in the bundle I see
/***/ ((module) => {
module.exports = require("express");
/***/ }),
I expect to get something like this
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
/***/ }),
I tried adding this code to config, but it didn't help
externals: [
nodeExternals(),
'express',
]
server.ts
import express from 'express';
const app = express();
app.get('/', (request, response) => {
response.send('Hi there');
});
app.listen(3000, () => {
console.log('Listen on the port 3000...');
});
The essence of the question is this: there is a build on webpack, everything works fine with one exception: when changing PUG files.
the project is rebuilt, but the content is not updated in the browser.
When building it produces an error: Entrypoint undefined = ./index.html
const path = require('path');
const fs = require('fs');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const TerserWebpackPlugin = require('terser-webpack-plugin');
const PATHS = {
src: path.join(__dirname, './src'),
dist: path.join(__dirname, './dist'),
assets: 'assets/',
pages: function () { return `${this.src}/pug/` }
}
// const PAGES_DIR = PATHS.src
const PAGES = fs.readdirSync(PATHS.pages()).filter(fileName => fileName.endsWith('.pug'));
const isDev = process.env.NODE_ENV === 'development'
const isProd = !isDev
const optimization = () => {
const config = {
splitChunks: {
chunks: 'all'
}
}
if (isProd) {
config.minimizer = [
new OptimizeCssAssetWebpackPlugin(),
new TerserWebpackPlugin()
]
}
return config
}
const filename = ext => isDev ? `[name].${ext}` : `[name].[hash].${ext}`
const cssLoaders = extra => {
const loaders = [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: isDev,
reloadAll: true
},
},
'css-loader'
]
if (extra) {
loaders.push(extra)
}
return loaders
}
const babelOptions = preset => {
const opts = {
presets: [
'#babel/preset-env'
],
plugins: [
'#babel/plugin-proposal-class-properties'
]
}
if (preset) {
opts.presets.push(preset)
}
return opts
}
const jsLoaders = () => {
const loaders = [{
loader: 'babel-loader',
options: babelOptions()
}]
if (isDev) {
loaders.push('eslint-loader')
}
return loaders
}
const plugins = () => {
const base = [
new CleanWebpackPlugin(),
new CopyWebpackPlugin([
{ from: `${PATHS.src}/${PATHS.assets}img`, to: `${PATHS.assets}img` },
{ from: `${PATHS.src}/${PATHS.assets}fonts`, to: `${PATHS.assets}fonts` },
{ from: `${PATHS.src}/static`, to: '' },
]),
new MiniCssExtractPlugin({
filename: filename('css')
}),
...PAGES.map(page => new HTMLWebpackPlugin({
template: `${PATHS.pages()}/${page}`,
filename: `./${page.replace(/\.pug/,'.html')}`,
}))
]
return base
}
module.exports = {
context: PATHS.src,
mode: process.env.NODE_ENV,
entry: {
app: PATHS.src,
},
output: {
filename: filename('js'),
path: PATHS.dist
},
resolve: {
extensions: ['.js', '.json', '.png'],
alias: {
'#': PATHS.src,
}
},
optimization: optimization(),
devServer: {
hot: isDev
},
devtool: isDev ? 'source-map' : '',
plugins: plugins(),
module: {
rules: [
{
test: /\.pug$/,
loader: 'pug-loader',
options: {
pretty: isProd
}
},
{
test: /\.css$/,
use: cssLoaders()
},
{
test: /\.s[ac]ss$/,
use: cssLoaders('sass-loader')
},
{
test: /\.(png|jpg|svg|gif)$/,
use: ['file-loader']
},
{
test: /\.(ttf|woff|woff2|eot)$/,
use: ['file-loader']
},
{
test: /\.xml$/,
use: ['xml-loader']
},
{
test: /\.csv$/,
use: ['csv-loader']
},
{
test: /\.js$/,
exclude: /node_modules/,
use: jsLoaders()
}
]
}
}
Project structure:
enter image description here
Have you tried html-webpack-pug-plugin?
npm i html-webpack-pug-plugin
Replace this:
const plugins = () => {
const base = [
//..
...PAGES.map(page => new HTMLWebpackPlugin({
template: `${PATHS.pages()}/${page}`,
filename: `./${page.replace(/\.pug/, '.html')}`,
}))
]
//...
With this:
const plugins = () => {
const base = [
//..
new HtmlWebpackPugPlugin(),
new HtmlWebpackPlugin({
template: './src/pug/index.pug',
filename: 'index.pug',
})
]
//...
The plugin will copy the main index.pug file into the dist directory with reference to js and css files.
The pug files in static directory should then load the main template file like this:
extends ../../dist/index.pug
I have solved this problem with additional package chokidar.
i use next code:
const chokidar = require('chokidar');
...
devServer: {
hot: true,
overlay: {
warnings: false,
errors: true
},
before(app, server) {
chokidar.watch([
`${PATHS.src}/**/*.pug`
]).on('all', function() {
server.sockWrite(server.sockets, 'content-changed');
})
}
}
...
I'm new to webpack and want to use html-critical-webpack-plugin in my vue.config.js file which is created by vue-cli3. But I get this error while using const path= require('path') in my vue.config.js file. I don't see any webpack.config.js file in my root folder. How do I get this working in vue.config.js file?
const path = require('path')
const HtmlCriticalPlugin = require("html-critical-webpack-plugin");
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin')
module.exports = {
configureWebpack: {
optimization: {
splitChunks: {
chunks: 'all',
},
},
plugins: [
new VuetifyLoaderPlugin(),
new HtmlCriticalPlugin({
base: path.join(path.resolve(__dirname), 'dist/'),
src: 'index.html',
dest: 'index.html',
inline: true,
minify: true,
extract: true,
width: 375,
height: 565,
penthouse: {
blockJSRequests: false,
}
})
]
},
devServer: {
disableHostCheck: true,
},
lintOnSave: false,
pwa: {
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'src/service-worker.js'
}
}
}
Is there anything wrong with my webpack config? I followed tutorials online everywhere says the same way to config. But I think I must have missed something.
webpack.common.js
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
// const HtmlWebpackPlugin = require('html-webpack-plugin');
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
library: './src/library.js',
HelloComp: './src/components/HelloComponent/HelloComponent.vue',
Bye: './src/components/ByeComponent/ByeComponent.vue',
MiniC: './src/components/MiniC/MiniC.vue',
TestAb: './src/components/test-ab/test-ab.vue'
},
plugins: [
new CleanWebpackPlugin(['dist'])
// Do not really need it as no live app is here
// new HtmlWebpackPlugin({
// title: 'Production'
// })
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: 'library',
libraryTarget: 'umd'
},
externals: {
'vue': {
root: 'vue',
commonjs2: 'vue',
commonjs: 'vue',
amd: 'vue',
umd: 'vue'
},
'vue-router': {
root: 'vue-router',
commonjs2: 'vue-router',
commonjs: 'vue-router',
amd: 'vue-router',
umd: 'vue-router'
}
// ,
// 'style-loader': {
// root: 'style-loader',
// commonjs2: 'style-loader',
// commonjs: 'style-loader',
// amd: 'style-loader',
// umd: 'style-loader'
// },
// 'vue-hot-reload-api': {
// root: 'vue-hot-reload-api',
// commonjs2: 'vue-hot-reload-api',
// commonjs: 'vue-hot-reload-api',
// amd: 'vue-hot-reload-api',
// umd: 'vue-hot-reload-api'
// },
// 'vue-loader': {
// root: 'vue-loader',
// commonjs2: 'vue-loader',
// commonjs: 'vue-loader',
// amd: 'vue-loader',
// umd: 'vue-loader'
// }
}
}
webpack.prod.js
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const webpack = require('webpack')
const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// const path = require('path')
// function resolve (dir) {
// return path.join(__dirname, '..', dir)
// }
const configedAnalyzer = new BundleAnalyzerPlugin({
// Can be `server`, `static` or `disabled`.
// In `server` mode analyzer will start HTTP server to show bundle report.
// In `static` mode single HTML file with bundle report will be generated.
// In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
analyzerMode: 'static',
// Host that will be used in `server` mode to start HTTP server.
analyzerHost: '127.0.0.1',
// Port that will be used in `server` mode to start HTTP server.
analyzerPort: 8887,
// Path to bundle report file that will be generated in `static` mode.
// Relative to bundles output directory.
reportFilename: './../report/bundle_anlaysis.html',
// Module sizes to show in report by default.
// Should be one of `stat`, `parsed` or `gzip`.
// See "Definitions" section for more information.
defaultSizes: 'gzip',
// Automatically open report in default browser
openAnalyzer: true,
// If `true`, Webpack Stats JSON file will be generated in bundles output directory
generateStatsFile: true,
// Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
// Relative to bundles output directory.
statsFilename: 'stats.json',
// Options for `stats.toJson()` method.
// For example you can exclude sources of your modules
// from stats file with `source: false` option.
// See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
statsOptions: null,
// Log level. Can be 'info', 'warn', 'error' or 'silent'.
logLevel: 'info'
})
module.exports = merge(common, {
mode: 'production',
module: {
rules: [
{
test: /\.vue$/,
use: 'vue-loader'
},
// IMPORTANT: All js load should come AFTER vue-loader!!!
{
test: /\.(js|vue)$/,
use: 'eslint-loader',
enforce: 'pre' // kick in before other loader... Q: also before vue-loader I suppose? maybe better move it to top?
},
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
filename: '[name].css'
}
},
'css-loader', // translates CSS into CommonJS
'sass-loader' // compiles Sass to CSS, using Node Sass by default
]
},
// {
// test: /\.css$/,
// use: [
// 'vue-style-loader',
// 'css-loader'
// ]
// },
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
// {
// test: /\.scss$/,
// use: [
// MiniCssExtractPlugin.loader,
// 'style-loader', // creates style nodes from JS strings
// 'css-loader', // translates CSS into CommonJS
// 'sass-loader' // compiles Sass to CSS, using Node Sass by default
// ]
// },
{
test: /\.js$/,
use: 'babel-loader'
}
]
},
plugins: [
// new webpack.HotModuleReplacementPlugin(),
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new CopyWebpackPlugin([{
// NOTE: it does not really do anything, unless we have a asset folder, that needed no compression
from: './static/',
to: './static/',
toType: 'dir'
}]),
// NOTE: honestly, this did not help reduce prod bundle size... but for wtw:
// https://webpack.js.org/plugins/module-concatenation-plugin/
new webpack.optimize.ModuleConcatenationPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
// NOTE: disable when needed, its just to analyze code
configedAnalyzer
],
stats: {
// Examine all modules
maxModules: Infinity,
// Display bailout reasons
optimizationBailout: true
}
});
To reproduce
git clone https://github.com/adamchenwei/boilerplate-webpack-babel-sass-storybook-vuejs
npm install
./p
siily me. I forgot to actually let the webpack to see the scss file by adding entry to it. and basically just do #import '...' in library-global-styles.scss. But would love to know how to do to break them down depends on file name though...
entry: {
...
'library-global-styles': './src/library-global-styles.scss'
},
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()
}