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

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.

Related

How can I make Jest look within node_modules?

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

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/"
]

Jest gives an error: "SyntaxError: Unexpected token export"

I'm using Jest to test my React app.
Recently, I added DeckGL to my app. My tests fail with this error:
Test suite failed to run
/my_project/node_modules/deck.gl/src/react/index.js:21
export {default as DeckGL} from './deckgl';
^^^^^^
SyntaxError: Unexpected token export
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:318:17)
at Object.<anonymous> (node_modules/deck.gl/dist/react/deckgl.js:9:14)
at Object.<anonymous> (node_modules/deck.gl/dist/react/index.js:7:15)
This looks like an issue with Jest transforming a node module before running it's tests.
Here is my .babelrc:
{
"presets": ["react", "es2015", "stage-1"]
}
Here is my jest setup:
"jest": {
"testURL": "http://localhost",
"setupFiles": [
"./test/jestsetup.js"
],
"snapshotSerializers": [
"<rootDir>/node_modules/enzyme-to-json/serializer"
],
"moduleDirectories": [
"node_modules",
"/src"
],
"moduleNameMapper": {
"\\.(css|scss)$": "<rootDir>/test/EmptyModule.js"
}
},
I seem to have the correct things necessary to transform export {default as DeckGL }. So any ideas whats going wrong?
This means, that a file is not transformed through TypeScript compiler, e.g. because it is a JS file with TS syntax, or it is published to npm as uncompiled source files. Here's what you can do.
Adjust your transformIgnorePatterns allowed list:
{
"jest": {
"transformIgnorePatterns": [
"node_modules/(?!#ngrx|(?!deck.gl)|ng-dynamic)"
]
}
}
By default Jest doesn't transform node_modules, because they should be valid JavaScript files. However, it happens that library authors assume that you'll compile their sources. So you have to tell this to Jest explicitly. Above snippet means that #ngrx, deck and ng-dynamic will be transformed, even though they're node_modules.
And if you are using 'create-react-app', it won't allow you to specify 'transformIgnorePatterns' via Jest property in package.json
As per this https://github.com/facebook/create-react-app/issues/2537#issuecomment-390341713
You can use CLI as below in your package.json to override and it works :
"scripts": {
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!your-module-name)/\"",
},
This is because Node.js cannot handle ES6 modules.
You should transform your modules to CommonJS therefore.
Babel 7 >=
Install
npm install --save-dev #babel/plugin-transform-modules-commonjs
And to use only for test cases add to .babelrc,
Jest automatically gives NODE_ENV=test global variable.
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
Babel 6 >=
npm install --save-dev babel-plugin-transform-es2015-modules-commonjs
to .babelrc
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
Jest by default won't compile files in the node_modules directory.
transformIgnorePatterns [array]
Default: ["/node_modules/"]
An array of regexp pattern strings that are matched against all source
file paths before transformation. If the test path matches any of the
patterns, it will not be transformed.Default: ["/node_modules/"]
DeckGL seems to be in ES6, to make jest able to read it, you need to compile this as well.
To do that, just add an exception for DeckGL in the transformignorePatterns
"transformIgnorePatterns": ["/node_modules/(?!deck\.gl)"]
https://facebook.github.io/jest/docs/en/configuration.html#transformignorepatterns-array-string
I was having this issue with a monorepo. A package in the root node_modules was breaking my tests. I fixed by changing my local .babelrc file to babel.config.js. Explanation: https://github.com/facebook/jest/issues/6053#issuecomment-383632515
It was work around #1 on this page that fixed it for me though workaround #2 on that page is mentioned in above answers so they may also be valid.
"Specify the entry for the commonjs version of the corresponding package in the moduleNameMapper configuration"
jest.config.js
moduleNameMapper: {
"^uuid$": require.resolve("uuid"),
"^jsonpath-plus$": require.resolve("jsonpath-plus")
...
In my case I use this config in the file package.json:
"jest": {
"transformIgnorePatterns": [
"!node_modules/"
]
}
This code worked for me
// .babelrc
{
"presets": [
["env", {
"modules": "commonjs", // <- Check and see if you have this line
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-vue-jsx", "transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"]
}
}
}
jest understands commonJs so it needs babel to transform the code for it before use. Also jest uses caching when running code. So make sure you run jest --clearCache before running jest.
Tested Environment:
Node v8.13.0
Babel v6+
Jest v27
I'm using a monorepo (it contains multiple packages for the frontend and backend).
The package I'm testing imports a file from another package that uses the dependency uuid.
All the files are in Typescript (not Javascript).
The package I'm testing has a tsconfig file for testing only, called tsconfig.test.json. It has the properties commonjs and allowJs. Adding allowJs solves the problem when importing uuid, I don't know why.
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": [
"jest",
"node"
],
// Necessary to import dependency uuid using CommonJS
"allowJs": true
},
"include": [
"jest.config.ts",
"**/*.test.ts",
"**/*.d.ts"
]
}
I was upgrading a project that uses a version of babel that reads the config from .babelrc, when I upgraded to a newer version I read:
https://babeljs.io/docs/en/configuration#whats-your-use-case
What's your use case?
You are using a monorepo?
You want to compile node_modules?
babel.config.json is for you!
On top of:
{
"jest": {
"transformIgnorePatterns": [
"node_modules/(?!(module))"
]
}
}
I renamed .babelrc to babel.config.json too.
I had the same error of importing dataSet from vis-data.js library
import { DataSet } from 'vis-data/esnext';
So I just removed /esnext from the path and now it works:
import { DataSet } from 'vis-data';

Webpack/Express - environment variables not found by server

In my Express/React app, I am using Webpack to handle server-side rendering. However, I am experiencing a build error related to environment variables that I'm trying to access in my Express server script.
In the server script, index.js, I am setting a few variables like so:
const gitCommit = process.env.GIT_COMMIT || require("./gitignore/git_commit.js"),
buildDate = process.env.BUILD_DATE || require("./gitignore/build_date.js")
And since I am running a test production build on my local machine, I delete the gitignore/ directory and set those environment variables:
$ export GIT_COMMIT="test commit hash"
$ export BUILD_DATE="test build date"
Then I npm run build, which executes the following scripts:
"build:client": "webpack --config webpack.config.js",
"build:server": "webpack --config webpack.server.config.js",
"build": "npm run build:client && npm run build:server"
build:client executes with no problem, but build:server throws errors...
ERROR in ./index.js
Module not found: Error: Can't resolve './gitignore/git_commit.js' in '/Users/filepath'
# ./index.js 12:38-74
ERROR in ./index.js
Module not found: Error: Can't resolve './gitignore/build_date.js' in '/Users/filepath'
# ./index.js 13:42-78
implying that the two environment variables referenced in index.js can't be found, and so it's looking for the gitignore/ instead, which shouldn't exist (I mean, it does exist locally, but I've deleted since I'm simulating a production build).
Here is the complete webpack.server.config.js:
const fs = require("fs"),
path = require("path")// ,
// ExtractTextPlugin = require("extract-text-webpack-plugin")
module.exports = {
"entry": path.resolve(__dirname, "index.js"),
// keep node_module paths out of the bundle
"externals": fs.readdirSync(path.resolve(__dirname, "node_modules")).concat(["react-dom/server", "react/addons"]).reduce((ext, mod) => {
ext[mod] = `commonjs ${mod}`
return ext
}, {}),
"module": {
"loaders": [
{
"exclude": /node_modules/,
"loader": "babel-loader",
"query": { "presets": ["react", "es2015", "stage-2"] },
"test": /\.jsx$/
},
{
"exclude": /node_modules/,
"loader": "babel-loader",
"query": { "presets": ["react", "es2015", "stage-2"] },
"test": /\.js$/
}
]
},
"node": {
"__dirname": true,
"__filename": true
},
"output": {
"filename": "server.bundle.js"
},
"target": "node"
}
Now I expect that gitignore/ would not be found, but what I don't understand is why the two environment variables that I set are not being detected by index.js - they are definitely set in the console before I even run the build command. If I console.log() them in the beginning of webpack.server.config.js, it logs them correctly, and if I run my development version instead (which doesn't use the server config), I can log them correctly in index.js. What gives?
Node version 6.11.1, NPM version 3.10.10, Webpack version 2.6.0.
Your environment variables are only available when Webpack runs, but not when you execute your index.js.
You will need to use the EnvironmentPlugin in your Webpack config like that:
plugins: [new webpack.EnvironmentPlugin(['GIT_COMMIT ', 'BUILD_DATE'])]
That plugin will replace the variables by their actual values.
HINT: Do not use ||. Webpack does not know how to optimize it. Try the ternary operator:
const gitCommit = (process.env.GIT_COMMIT) ? (
process.env.GIT_COMMIT
) : (
require('./gitignore/git_commit.js')
);
Webpack will bundle this to:
const gitCommit = (true) ? (
"test commit hash"
) : (
require('./gitignore/git_commit.js')
);
No IgnorePlugin is needed. Even better, with the UglifyJSPlugin, your code will be optimized to const gitCommit = "test commit hash";. In some cases gitCommit is removed completely as a variable. Its string value will be used instead anywhere where you applied gitCommit.

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