Jest passing tests but --covering option not picking up files - node.js

Problem description:
I have written two tests for a typescript class. Those two tests pass so jest successfully retrieves the test files. I then use the --coverage option but it appears jest is not picking the covered files here.
Here is the output I am getting:
api_jester | PASS src/tests/repositories/user.test.ts
api_jester | User Repository
api_jester | ✓ it should return an empty array (18ms)
api_jester | ✓ should successfully create a user and return its data (7ms)
api_jester |
api_jester | ----------|----------|----------|----------|----------|-------------------|
api_jester | File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
api_jester | ----------|----------|----------|----------|----------|-------------------|
api_jester | All files | 0 | 0 | 0 | 0 | |
api_jester | ----------|----------|----------|----------|----------|-------------------|
api_jester | Test Suites: 1 passed, 1 total
api_jester | Tests: 2 passed, 2 total
api_jester | Snapshots: 0 total
api_jester | Time: 3.208s
api_jester | Ran all test suites.
I have tried playing with the collectCoverageFrom option but without any success. I have tested covering with some simple examples found on github and those were working so the problem is not from my environment. I am guessing I somehow missed something in my configuration but I have spend so much time on this I am getting kind of frustrated so maybe some fresh looks could help..
Project architecture :
config
|__ jest.config.js
|__ tsconfig.json
src
|__tests
| |__repositories
| |__user.test.ts
|__repositories
|___ userRepository
|__User.ts
Jest.config.js :
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["../src/tests/"],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
collectCoverageFrom: ["../src/"],
moduleFileExtensions: ["ts", "js", "json"],
coverageDirectory: "../coverage"
};
package.json
{
"name": "theralog_api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"build": "tsc",
"prettier": "npx prettier --write src/**/*.ts --config ./config/.prettierrc",
"eslint": "npx eslint --config ./config/.eslintrc ./src/**/**/*",
"start:dev": "npx nodemon -L --config ./config/api.nodemon.json",
"test:watch": "npx nodemon -L --config ./config/jester.nodemon.json",
"test:coverage": "npx jest --config ./config/jest.config.js --coverage --colors --watch"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#types/compression": "^1.0.1",
"#types/express": "^4.17.1",
"#types/graphql-depth-limit": "^1.1.2",
"#types/jest": "^24.0.23",
"#types/node": "^12.7.12",
"#typescript-eslint/eslint-plugin": "^2.5.0",
"#typescript-eslint/parser": "^2.5.0",
"apollo-server-testing": "2.9.7",
"babel-jest": "^24.9.0",
"eslint": "^6.5.1",
"eslint-config-prettier": "^6.4.0",
"graphql-depth-limit": "^1.1.0",
"graphql-import": "^0.7.1",
"graphql-import-node": "0.0.4",
"jest": "^24.9.0",
"nodemon": "^1.19.3",
"prettier": "^1.18.2",
"ts-jest": "^24.1.0",
"ts-node": "^8.4.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.7.2"
},
"dependencies": {
"apollo-server-express": "^2.9.6",
"compression": "^1.7.4",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"graphql": "^14.5.8",
"http": "0.0.0",
"lodash": "^4.17.15",
"ncp": "^2.0.0",
"pg": "^7.12.1",
"winston": "3.2.1"
}
}
jester.nodemon.json
{
"watch": ["../src"],
"ext": "ts",
"exec": "npx jest --config ./config/jest.config.js --watchAll"
}

You are missing a setting in the jest.config.js, collectCoverage: true
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["../src/tests/"],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
collectCoverage: true,
collectCoverageFrom: ["../src/"],
moduleFileExtensions: ["ts", "js", "json"],
coverageDirectory: "../coverage"
};
I also use a more descriptive collectCoverageFrom:
collectCoverageFrom: [
'<rootDir>/src/**/*.ts',
'!<rootDir>/src/**/*.interface.ts',
'!<rootDir>/src/**/*.mock.ts',
'!<rootDir>/src/**/*.module.ts',
'!<rootDir>/src/**/*.spec.ts',
'!<rootDir>/src/**/*.test.ts',
'!<rootDir>/src/**/*.d.ts'
],
This way I exclude a number of files I do not want to count coverage from, such as my modules, mocks, and tests.
My full file with the original Jest init process and the comments from that.
For a detailed explanation regarding each configuration property, visit: the Jest documentation
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after the first failure
// bail: false,
// Respect "browser" field in package.json when resolving modules
// browser: false,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\sscott\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls and instances between every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: [
'<rootDir>/src/**/*.ts',
'!<rootDir>/src/**/*.mock.ts',
'!<rootDir>/src/**/*.module.ts',
'!<rootDir>/src/**/*.spec.ts',
'!<rootDir>/src/**/*.test.ts',
'!<rootDir>/src/**/*.d.ts'
],
// The directory where Jest should output its coverage files
coverageDirectory: "<rootDir>/docs",
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
"\\\\node_modules\\\\"
],
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: [
"lcov",
"clover",
"text-summary"
],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: null,
// Make calling deprecated APIs throw helpful error messages
errorOnDeprecated: true,
// Force coverage collection from ignored files usin a array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: null,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: null,
// A set of global variables that need to be available in all test environments
globals: {
"ts-jest": {
"diagnostics": false,
"tsConfig": "tsconfig.json"
}
},
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
moduleFileExtensions: [
"ts",
"tsx",
"js"
],
// A map from regular expressions to module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "always",
// A preset that is used as a base for Jest's configuration
// preset: null,
// Run tests from one or more projects
// projects: null,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: null,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: null,
// A list of paths to directories that Jest should use to search for files in
roots: [
"<rootDir>/src"
],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// The path to a module that runs some code to configure or set up the testing framework before each test
// setupTestFrameworkScriptFile: null,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: [
"**/*.spec.ts"
],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern Jest uses to detect test files
// testRegex: "",
// This option allows the use of a custom results processor
// testResultsProcessor: null,
// "testResultsProcessor": "jest-jenkins-reporter",
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
transform: {
"^.+\\.(ts|tsx)$": "ts-jest"
},
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
verbose: false
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};

After a lot of research at several pages, this worked for me to get the coverage report:
put below line under scripts:
"test:coverage": "set CI=true && react-scripts test --coverage",
And, add below code for jest configuration in package.json file as below:
"jest": {
"collectCoverageFrom": [
"**/*.{js,jsx}",
"!**/node_modules/**",
"!**/coverage/**",
"!**/serviceWorker.js",
"!**/index.js"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"package.json",
"package-lock.json"
]
}
And, then run
npm run test:coverage

Apparently you have to add your source files to roots to make it work. See this PR comment.
Instead of this:
roots: ["../src/tests/"]
Also include your source files:
roots: ["../src/tests/", "../src/repositories/"]
After that and having the correct collectCoverageFrom, all files with 0% coverage were detected as expected.

Related

Jest and Babel transpilation - SyntaxError: Cannot use import statement outside a module

I struggle to use JEST for some cases where running the tests I get
Test suite failed to run
...node_modules\p-retry\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import retry from 'retry';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import pRetry from 'p-retry';
| ^
2 |
3 | export function Retry(tries: number) {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/common/Retry.ts:1:1)
Meanwhile my webpack build works nice with typescript and babel. I tried a lot of stuff (see below to get it working but no success so far - and haven't really been able to understand whats going on. From my pov - though the transpilation stuff is kind of a black area so far for me I tried to enable Jest to use ESModules andprovide code as such as well as tried providing commonJS module code.
So I am looking for alternative options and ways to investigate further. Particularly one thing strikes me as strange:
the Retry.ts file from the error is one of my files which imports the pRetry (a node_module written in ESModule style) which in its code does the import retry from 'retry' (another node-module written in commonJS style)from the very first line of the error.
So what seems to happen to me is that the pRetry is not transformed from it's ESModule Code (the source of pRetry starts with import retry from 'retry';) and just wrapped in some commonJS code instead if I interpret the syntax correctly.
So my next steps would likely be investigate what babel-jest really generates and check what's up there and try to deduct furhter. Does anybody know how to achieve this (especially understand what babel-jest generates) or has another idea?
Things I tried - all failed (sometimes slightly different errors)
using plugins: ["#babel/plugin-transform-runtime"] in babel.config.js
changing target and module in tsconfig.json to es5
introducing below in jest.config.ts transformIgnorePatterns: ["node_modules/?!(p-retry)"]
using the following in jest.config.ts
preset: "ts-jest",
transform: {
'^.+\.(ts|tsx)?$': 'ts-jest',
"^.+\.(js|jsx)$": "babel-jest"}
or alternatively with ts-jest for both or babel-jest for both
migrating from .babelrc file to babel.config.js as suggested by one post
AllowJS : true in tscfonfig.json and transformIgnorePatterns in jest in combination
adding ["#babel/plugin-transform-runtime",{"regenerator": true}] to babel.config
Using
preset: "ts-jest",
testEnvironment: "node",
transform: {"node_modules/p-retry/.+\.(j|t)sx?$": "ts-jest"},
transformIgnorePatterns: ["node_modules/(?!p-retry/.*)"]
in jest.config
using "transform-es2015-modules-commonjs" in babel.config
using #babel/plugin-transform-modules-commonjs in babel.config
Applying the following steps as suggest by https://stackoverflow.com/questions/35756479/does-jest-support-es6-import-export#:~:text=Jest%20will%20enable%20compilation%20from,json%20.&text=If%20you%20don't%20want%20to%20pollute%20your%20project%20with%20
Make sure you don't transform away import statements by setting
transform: {} in config file
Run node#^12.16.0 || >=13.2.0 with --experimental-vm-modules flag
Run your test with jest-environment-node or jest-environment-jsdom-sixteen.
playing with testenvironment like jest-environment-node, node or jsdom in jest.config.ts
jest-config.ts:
const tsconfig = require("./tsconfig.json");
const moduleNameMapper = require("tsconfig-paths-jest")(tsconfig)
export default {
collectCoverage: true,
coverageDirectory: "analysis/coverage",
coveragePathIgnorePatterns: ["/node_modules/"],
collectCoverageFrom: ["src/**/*.{js,jsx,ts}"],
coverageReporters: ["json", "lcov", "text", "clover"],
coverageThreshold: {
global: {
branches: 0,
functions: 0,
lines: 0,
statements: 0
},
},
clearMocks: true,
coverageProvider: "babel",
moduleNameMapper,
roots: ["<rootDir>/src/", "<rootDir>/test/"],
testEnvironment: 'jest-environment-node',
testPathIgnorePatterns: [
"\\\\node_modules\\\\"
],
"transform": {
"^.+\\.(js|ts|jsx)$": "babel-jest"
}
};
babel.config.js:
module.exports = {
presets: ['#babel/preset-typescript',
['#babel/preset-env', {
targets: { node: "current" }
}],
'#babel/preset-flow',
],
plugins: [["#babel/plugin-transform-modules-commonjs"], ["#babel/plugin-proposal-decorators", { "legacy": true }], ["#babel/plugin-proposal-class-properties"]]
}
Extract from package.json
"#babel/core": "^7.16.12",
"#babel/plugin-proposal-decorators": "^7.16.5",
"#babel/plugin-transform-modules-commonjs": "^7.16.8",
"#babel/plugin-transform-runtime": "^7.16.10",
"#babel/preset-env": "^7.14.4",
"#babel/preset-flow": "^7.16.7",
"#babel/preset-typescript": "^7.13.0",
"#babel/runtime": "^7.16.7",
"babel-jest": "^27.4.6",
"babel-plugin-transform-regenerator": "^6.26.0",
"jest": "^27.0.4",
"jest-config": "^27.4.5",
"jest-esm-transformer": "^1.0.0",
"ts-jest": "^27.1.3",
"tsconfig-paths-jest": "^0.0.1",
"core-js": "^3.20.0",
Turns out I was close.
With a change of babel.config.ts by adding esmodules: false it is done :-)
module.exports = {
presets: ['#babel/preset-typescript',
['#babel/preset-env', {
targets: { esmodules: false, node: "current" }
}],
'#babel/preset-flow',
],
plugins: [["#babel/plugin-transform-modules-commonjs"], ["#babel/plugin-proposal-decorators", { "legacy": true }], ["#babel/plugin-proposal-class-properties"]]
}
My solution with "jest": "^28.1.0":
In package.json
under devDependencies add:
"#babel/preset-env": "^7.18.10"
and,
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
}
},
In babel.config.json add:
{
"presets": ["#babel/preset-env"]
}
You can let Jest do not ignore transforming p-retry by adding this in your jest. config.js, it works for me.
"transformIgnorePatterns": [
"node_modules/(?!(p-retry)/)",
],
In my case I had to add specific module mappings as detailed here: https://stackoverflow.com/a/65250052/285549
This forces Jest to load the CommonJS version of the module since the tests are running in Node even though the eventual target is the browser.

Jest recommends use --detectOpenHandles but with --detectOpenHandles nothing special happen

I always get this message printed when I run my tests with jest --silent:
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
But when I run jest --silent --detectOpenHandles nothing special happens, no extra message, no warning, nothing. It just completes correctly.
I am using:
"jest": "^26.6.3",
"jest-extended": "^0.11.5",
"jest-preset-angular": "^8.3.2",
"ts-jest": "^26.4.4",
"ts-mockito": "^2.6.1",
and my config is:
const ignoredFiles = [
'<rootDir>/src/test.ts',
'<rootDir>/src/main.ts',
'<rootDir>/src/jest-global.mocks.ts',
'<rootDir>/src/polyfills.ts',
'<rootDir>/src/test-helpers.ts',
'<rootDir>/src/mocks',
'<rootDir>/plugins/',
'<rootDir>/coverage/',
'<rootDir>/scripts/',
'<rootDir>/android/',
'<rootDir>/e2e/',
'<rootDir>/ssd_hooks/',
'<rootDir>/typings/',
'<rootDir>/platforms/',
'<rootDir>/plugins/',
'<rootDir>/resources/',
'<rootDir>/manual-plugins/'
];
module.exports = {
preset: 'jest-preset-angular',
setupFilesAfterEnv: ['<rootDir>/src/setupJest.ts'],
transformIgnorePatterns: ['<rootDir>/node_modules/(?!#ionic|#saninn|#ngrx|#capacitor-community)'],
coverageReporters: process.env.CI ? ['text'] : ['lcov'],
testPathIgnorePatterns: ['/node_modules/', ...ignoredFiles],
modulePathIgnorePatterns: ['<rootDir>/coverage/', '<rootDir>/plugins/'],
collectCoverage: false,
notify: true,
coverageDirectory: './coverage',
collectCoverageFrom: ['<rootDir>/src/**/*.ts', '!**/*.module.ts', '!**/*.enum.ts'],
coveragePathIgnorePatterns: ['/node_modules/', 'package.json', ...ignoredFiles],
globals: {
'ts-jest': {
tsconfig: '<rootDir>/src/tsconfig.spec.json',
diagnostics: {
ignoreCodes: [
6138, // declared but never read
6133, // declared but never used,
2322 // object should just have known keys
]
}
}
}
};
How can I find what is causing jest to show that warning?

How can I target node with gulp-babel

I am trying to transpile my coffee code to run mocha tests inside a gulp task.
I get [BABEL] /some/path/example.js: Unknown option: .targets. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.
Here is the relevant section of the gulp task:
.pipe(sourcemaps.init())
.pipe(gulpif(isCoffee, coffee({ bare: true })))
.pipe(babel({ presets: [
'#babel/preset-env', {
targets: {
node: "11.10"
}
}
]
} ))
.pipe(sourcemaps.write('.'))
.pipe(mocha({ reporter: 'list' }));
}
And the dependencies are:
"#babel/cli": "^7.2.3"
"#babel/core": "^7.3.3"
"#babel/preset-env": "^7.3.1"
"#babel/register": "^7.0.0"
...
"gulp": "^4.0.0"
"gulp-babel": "^8.0.0"
...
And the options are documented here .
I think I must have missed a memo somewhere!
Ah ha! This is missing a pair of square brackets: presets should contain an array of arrays, each inner array containing a preset name and optionally a map of options.
[
'preset-name', {
options-key: 'option value'
}
]
]
})).etcetera ```

Jest gives `Cannot find module` when importing components with absolute paths

Receiving the following error when running Jest
Cannot find module 'src/views/app' from 'index.jsx'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object.<anonymous> (src/index.jsx:4:12)
index.jsx
import AppContainer from 'src/views/app';
package.json
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleDirectories": [
"node_modules",
"src"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
},
My tests that run files that only contain relative paths in the tree run correctly.
To Clarify, I'm looking for how to configure Jest to not fail on absolute paths.
I think you're looking for: roots or modulePaths and moduleDirectories
You can add both relative and absolute paths.
I would make sure to include <rootDir> in the roots array, <rootDir> in the modulePaths array, and node_modules in the moduleDirectories array, unless you've got a good reason to exclude them.
"jest": {
"roots": [
"<rootDir>",
"/home/some/path/"
],
"modulePaths": [
"<rootDir>",
"/home/some/other/path"
],
"moduleDirectories": [
"node_modules"
],
}
Since in package.json you have:
"moduleDirectories": [
"node_modules",
"src"
]
Which says that each module you import will be looked into node_modules first and if not found will be looked into src directory.
Since it's looking into src directory you should use:
import AppContainer from 'views/app';
Please note that this path is absolute to the src directory, you do not have to navigate to locate it as relative path.
OR you can configure your root directory in moduleDirectories inside your pakcage.json so that all your components could be imported as you want it.
Adding
"moduleDirectories": [
"node_modules",
"src"
]
should work if you have Jest's config in your package.json file.
If you have a jest.config.js file, you should add it there, otherwise package.json will be overriden (and ignored) by this config file. So in your jest.config.js file:
module.exports = {
// ... lots of props
moduleDirectories: ["node_modules", "src"],
// ...
}
That's because jest doesn't recognize relative imports like src/views/app
Add a rootDir and a modulePaths in package.json
"name": "my-app",
...
"jest": {
...
"rootDir": "./",
"modulePaths": [
"<rootDir>"
],
...
}
}
Make sure you have run npm i or npm install after update the package.json. My issue was that :0
For those who are building something from scratch with Webpack and Babbel.
Try the following steps:
Delete the node_modules folder and install again. (This was something that solved my issue).
Here is a link with the necessary documentation to set up Webpack which in some cases will not be necessary. Jest Docs Webpack
Here is a link to the docs that explains how to set up Jest with React (Without using Create-React-App). Jest React Docs
4. Here is an example with a simple setup with Jest. You can set this up in package.json or the Jest configuration file.
Disclaimer: This does not answer the OP question. But most people will end up here for the keywords used for this issue.
"jest": {
"moduleFileExtensions": ["js", "jsx"],
"moduleDirectories": ["node_modules"],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
},
In my case, I was running integration tests and all tests were in the same file with the path src/int-test.spec.ts in order to read paths I had to write:
"jest": {
...,
"moduleNameMapper": {
"src/(.*)": "<rootDir>/$1"
}
}
Adding __esModule:true fixed this issue for me.
jest.mock('module',()=>({
__esModule: true, // this makes it work
default: jest.fn()
}));
Hope this helps somebody. Although this is not very specific to the question.
This can also be caused by absolute imports present in the globalSetup file (or any files it references).
It seems like moduleNameMappers do not get applied to globalSetup files. I fixed this by just switching to relative imports for those specific files.
This Workaround:
Using "moduleNameMapper" in your jest configuration will make test-resolve work as expected:
"jest": {
"moduleNameMapper": {
"#(.*)": "<rootDir>/node_modules/$1"
}
}
https://gist.github.com/lydell/d62ce96c95c035811133a5396195da14
One of the modules I wanted to use has a .cjs extension.
Adding .cjs to moduleFileExtensions in jest.config.js fixed this problem for me.
My jest.config.js as example:
module.exports = {
moduleNameMapper: {
// see: https://github.com/kulshekhar/ts-jest/issues/414#issuecomment-517944368
"^#/(.*)$": "<rootDir>/src/$1",
},
preset: "ts-jest/presets/default-esm",
globals: {
"ts-jest": {
useESM: true,
},
},
testEnvironment: 'jsdom',
transform: {
'^.+\\.vue$': 'vue3-jest',
},
moduleFileExtensions: ['json', 'js', 'jsx', 'ts', 'tsx', 'vue', "cjs"],
moduleDirectories: ["node_modules"],
};
Just add "modulePaths" to your package.json
"jest": {
...
"modulePaths": [
"<rootDir>"
],
...
}
}
I had jest-expo installed, but not jest. Probably related that I'm prebuild-ejected from Expo. I had to run yarn add jest-expo jest to install jest, and updated jest-expo. Now my tests run.
Depending on your setup it might be, npm i jest-expo jest or expo install jest-expo jest. ... Got the idea from their docs https://docs.expo.dev/guides/testing-with-jest/

Use Jest and spread operator without babel?

Is it possible to use the spread operator in code with Jest and without babel if the node engine is 8+?
I am dropping support for Node.js <8 in my app and assumed I could remove all babel dependencies and transpiling from package.json, however npm run jest fails immediately with these types of errors:
FAIL test/workers/repository/onboarding.spec.js
● Test suite failed to run
/Users/me/project/lib/workers/repository/onboarding.js: Unexpected token (13:17)
11 |
12 | async function createOnboardingBranch(inputConfig) {
> 13 | let config = { ...inputConfig };
| ^
Is there any way to get Jest to work without needing to add back all the babel dependencies and configuration?
Node.js version: 8.9.0
Jest version: 20.0.4
jest config in package.json:
"jest": {
"cacheDirectory": ".cache/jest",
"coverageDirectory": "./coverage",
"collectCoverage": true,
"collectCoverageFrom": [
"lib/**/*.js"
],
"coverageReporters": [
"json",
"lcov",
"text-summary"
],
"setupTestFrameworkScriptFile": "./test/chai.js"
},
Edit:
I have been able to narrow my babel configuration down to just one plugin: babel-plugin-transform-object-rest-spread and configure babel in package.json like so:
"babel": {
"plugins": [
"transform-object-rest-spread"
]
},
Taking this out or attempting to use babel-preset env causes Jest to fail on the spread operator again.

Resources