How can I make Jest look within node_modules? - jestjs

I've tried every combination of settings and overriding defaults, I cannot get Jest to look within my node_modules folder.
{
"testEnvironment": "node",
"testMatch": ["**.test.js"],
"testPathIgnorePatterns": []
}
Why wouldn't this work?
When I run jest with this config, with tests available in the node_modules folder, I get:
211 files checked.
testMatch: **.test.js - 0 matches
testPathIgnorePatterns: - 0 matches
testRegex: - 0 matches
Pattern: - 0 matches

Related

Why doesn't Jest configuration defined by 'testMatch' option match any of my test files within my project?

This is how my Jest config file looks:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>'],
moduleDirectories: ['node_modules', 'server'],
globals: {
'ts-jest': {
tsconfig: './tsconfig.test.json',
},
},
watchPathIgnorePatterns: ['/node_modules'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
testMatch: ['/**/*.test.(ts|tsx)'],
globalSetup: './global-setup.js',
};
and this is the output I get when I run jest -c jest.config.js in the project's root directory:
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In C:\Users\xxx\Documents\xxx\xxx\xxx
432 files checked.
testMatch: /**/*.test.(ts|tsx) - 0 matches
testPathIgnorePatterns: \\node_modules\\ - 432 matches
testRegex: - 0 matches
Pattern: - 0 matches
I had a feeling this might be related to different path separators on Windows and Linux. I'm running on Windows. So I tried changing the testMatch to ['\\**\\*.test.(ts|tsx)'] in jest.config.js. That did not resolve my issue.
I have 2 NPM scripts defined inside my package.json that produce the same output as above:
"lint-and-test": "npm run lint && npm run test"
"test": "jest --coverage --verbose"
This has been a known issue for a while with Jest. See the Issue titled testMatch on Windows #7914 for more context.
In windows default slash for file paths look like one\two\three\file.test.ts, but Jest does not seem to internally convert \\(escaped Windows style) or /(Unix style) path separators correctly thereby resulting in not picking up any of the test files.

Jest is not generating the report table in my terminal

The issue I'm facing is the lack of report tables in my terminal once I run my npm test.
I know for a fact that the reports are being generated, since I can see the files in the coverage directory.
However, it's a bit annoying and despite my debugging, I can't seem to find out what the issue is.
Here is my jest.config.js:
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/en/configuration.html
*/
module.exports = {
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
reporters: [
"default",
[
"jest-junit",
{
outputDirectory: "./coverage",
outputName: "unit_tests_coverage.xml",
},
],
],
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: ["cobertura", "lcov"],
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
maxWorkers: "50%",
// A list of paths to directories that Jest should use to search for files in
roots: ["test"],
testEnvironment: "node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
testRegex: ["/test/.*\\.(test|spec)?\\.(ts|tsx)$"],
transform: {
"^.+\\.ts?$": ["babel-jest"],
},
}
At the end of every test execution, I get like a summary like this:
Test Suites: 9 passed, 9 total
Tests: 155 passed, 155 total
Snapshots: 0 total
Time: 10.248 s
But no table showing line coverage, branch coverage... etc.
Is my jest.config.js incorrect or am I missing something?
Thanks in advance for your help!
Thanks to #jonrsharpe, I managed to find out what the issue was.
Since I was using reporters, the default one (text) was overridden. So in order to see it again, I had to specify it manually (check docs)
...
coverageReporters: ["cobertura", "lcov", "text"],
...

jest#23.1.0 collectCoverageFrom not picking the files outside root directory

When I run code coverage, code inside the root directory containing jest config works perfectly but for the code outside the root directory test cases passes but in the coverage report it shows zero percentage for all the test files outside the root directory.
jest.config.js file is inside explorebook folder.
directory structure:
|---core
| |--components
| |--test
| |--jest.setup.suites.js
|---explorebook
| |--components
| | |--test
| |--package.json
| |--jest.config.js
| |--jest.setup.suites.js
|---framework
| |--commons
| |--test
| |--jest.setup.suites.js
|
jest.config.js
const TEST_FILES_REGEX = '(/test/.*|(\\.|/)(test|spec))\\.js$';
module.exports = {
verbose: false,
roots: [
'<rootDir>/',
'<rootDir>/../core/',
'<rootDir>/../framework/commons/'
],
collectCoverage: true,
collectCoverageFrom: [
'components/**/*.js',
'<rootDir>/../core/components/**/*.js'
'<rootDir>/../framework/commons/*.js'
],
coverageDirectory: 'reports/coverage',
coverageReporters: [
'lcov',
'text'
],
setupFiles: [ '<rootDir>/jest.setup.suites.js',
'<rootDir>/../core/jest.setup.suites.js',
'<rootDir>/../framework/jest.setup.suites.js' ],
setupTestFrameworkScriptFile: path.join(__dirname, 'jest.setup.tests.js'),
testEnvironment: 'jsdom',
testRegex: TEST_FILES_REGEX
};
coverage report
Even if all the outside the rootDir passes, report does not show that.
I would expect the coverage values for files outside also to be correct in the report.
Jest will retrofit code coverage only on files inside the project's rootDir (source). In your setup, this will be the explorebook folder.
To also run coverage on files in a different folder than the one containing jest.config.js, I suggest setting [rootDir] (source) to your project's root folder, and update any necessary paths:
jest.config.js
const TEST_FILES_REGEX = '(/test/.*|(\\.|/)(test|spec))\\.js$';
module.exports = {
verbose: false,
rootDir: './../' // This should point to your project root folder
collectCoverage: true,
collectCoverageFrom: [
'**/*.js',
],
coverageDirectory: '<rootDir>/explorebook/reports/coverage',
coverageReporters: [
'lcov',
'text'
],
setupFiles: [ '<rootDir>/explorebook/jest.setup.suites.js',
'<rootDir>/core/jest.setup.suites.js',
'<rootDir>/framework/jest.setup.suites.js' ],
setupTestFrameworkScriptFile: path.join(__dirname, 'jest.setup.tests.js'),
testEnvironment: 'jsdom',
testRegex: TEST_FILES_REGEX
};

Jest tests not found

I have the following output in a gitlab job:
yarn run v1.15.2
$ jest --verbose
No tests found
In /path/to/my/project/
47 files checked.
testMatch: - 47 matches
testPathIgnorePatterns: /node_modules/,/build,/lib/ - 0 matches
testRegex: (/__tests__/.*|\.(test|spec))\.(tsx?|jsx?)$ - 1 match
Pattern: - 0 matches
Tests are not being executed, what am I doing wrong in here? I've been using the same gitlab-ci.yml config in other projects.
Any help would be appreciated!
Yes, the mistake was in package.json, I was missing <rootDir> in testPathIgnorePatterns and modulePathIgnorePatterns paths under jest options.
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/build",
"<rootDir>/lib/"
],
"modulePathIgnorePatterns": [
"<rootDir>/dist/",
"<rootDir>/build/"
]
The mistake is in your path. First open your cmd and navigate to directory where your package.json resides and then make sure whatever path you have provided in package.json, it must get-able.
You can also try to hard-code the path. Once you are able to run it then go for regex.
package.json
"name": "test",
"jest": {
"transform": {},
"verbose": true,
"bail": true,
"testMatch": ["path"]
},
For more details: testPathIgnorePatterns, modulePathIgnorePatterns
"testPathIgnorePatterns": [
"<rootDir>/build"
],
"modulePathIgnorePatterns": [
"<rootDir>/build/"
]

How to fix Jest "No Tests Found" on windows 10?

I am trying to use Jest on my windows 10 desktop computer, but it keeps telling me that there are no tests found. On my windows 10 laptop, it works just fine. Here is the output I am getting on my desktop:
C:\app> jest
No tests found
In C:\app
25163 files checked.
testMatch: **/__tests__/**/*.js?(x),**/?(*.)(spec|test).js?(x) - 743 matches
testPathIgnorePatterns: \\node_modules\\ - 25163 matches
Pattern: "" - 0 matches
In my package.json file, my jest config looks like this:
"jest": {
"collectCoverageFrom": [
"app/**/*.{js,jsx}",
"!app/**/*.test.{js,jsx}",
"!app/*/RbGenerated*/*.{js,jsx}",
"!app/app.js"
],
"coverageThreshold": {
"global": {
"statements": 98,
"branches": 91,
"functions": 98,
"lines": 98
}
},
"moduleDirectories": [
"node_modules",
"app",
"common"
],
"moduleNameMapper": {
".*\\.(css|less|styl|scss|sass)$": "<rootDir>/internals/mocks/cssModule.js",
".*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/internals/mocks/image.js"
},
"setupTestFrameworkScriptFile": "<rootDir>/internals/testing/test-bundler.js"
}
I am using node 8.1.4 and jest v20.0.4
Any ideas on how to get jest to locate my tests?
I am not 100% sure its the same issue. But what solved it for me was to get rid of watchman (I added it in on path for another project that used relay). Try to run with --no-watchman (or set watchman: false in jest config)
Seeing this issue with Jest 24.8.0. It seems if you add --runTestsByPath it will correctly handle forward/backspaces,
There is a discussion of the issue https://github.com/microsoft/vscode-recipes/issues/205#issuecomment-533645097, with the following suggested VSCode debug configuration
{
"type": "node",
"request": "launch",
"name": "Jest Current File",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": [
"--runTestsByPath", // This ensures the next line is treated as a path
"${relativeFile}", // This path may contain backslashes on windows
"--config",
"jest.config.js"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest",
}
}
For anyone attempting to find out how to fix this issue, this was a bug in Jest that was fixed in v22.
Changelog:
https://github.com/facebook/jest/blob/master/CHANGELOG.md (PR #5054)
If I run the console command
jest test/components/checkBox/treezCheckBox.test.js
the tests in that file are found and executed.
If I instead run the console command
jest test\components\checkBox\treezCheckBox.test.js
I get the error
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In D:\treezjs
814 files checked.
testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 44 matches
testPathIgnorePatterns: \\node_modules\\ - 814 matches
testRegex: - 0 matches
Pattern: test\components\checkBox\treezCheckBox.test.js - 0 matches
=> It seems to be important if forward or backward slashes are used.
Using doubled backward slashes works:
jest test\\components\\checkBox\\treezCheckBox.test.js
If you use a vscode launch configuration with a file path variable ${file}, the resulting system command unfortunately contains single "\" as separator.
Also see discussion and linked issues at https://github.com/Microsoft/vscode/issues/40256
(Last statement is outdated; ${relativeFile} also uses "\".)
Work around: Use a debug extension (e.g. Daddy Jest) instead of a custom launch configuration.
I have removed -- --watch from package.json where I wrote "test" : "jest -- --watch"

Resources