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

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"

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 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';

How to use nodemon with JSX?

I can compile and run my JSX app with one command:
jsx app.jsx | node
But I also want my server to automatically restart every time I modify app.jsx. I can do that with nodemon, but I can't quite figure out how to get nodemon to run my script through the JSX compiler beforehand.
I've got a nodemon.json file set up like this:
{
"execMap": {
"js": "node",
"jsx": "jsx {{filename}} | node"
},
"ext": "js jsx",
"ignore": [
".hg",
"node_modules",
".idea"
],
"verbose": true
}
But when I run nodemon it tells me:
8 Feb 21:58:48 - [nodemon] starting `jsx app.jsx | node`
8 Feb 21:58:48 - [nodemon] child pid: 10976
'\"jsx app.jsx | node\"' is not recognized as an internal or external command,
operable program or batch file.
Which is odd, because that command works verbatim when I paste it directly into my terminal.
Is there any way I get nodemon to run my JSX files?
It seems nodemon is attempting to run a program with the name you provide, rather than executing a shell.
Create a jsx.sh file with this content:
#!/bin/sh
jsx "$1" | node
Then chmod +x jsx.sh, and put this in your nodemon.json:
{
"execMap": {
"js": "node",
"jsx": "./jsx.sh"
},
"ext": "js jsx",
"ignore": [
".hg",
"node_modules",
".idea"
],
"verbose": true
}
* not tested
OR you can just locate the jsx command in your ./node_modules/.bin directory and run it off that instead:
{
script: "client.js",
options: {
execMap: {
"js": "node",
"jsx": "./node_modules/.bin/jsx \"$1\" | node"
},
ext: "js jsx",
callback: function (nodemon) {
nodemon.on("log", function (event) {
console.log(event.colour);
});
},
ignore: [
"node_modules/**/*.js",
"public/js/**",
"lib/api/**",
]
}
}
If you're on Windows (like me) you can create a .bat instead of a .sh like FakeRainBrigand suggests
#echo off
jsx %1 | node
This file has to be in the same directory as nodemon.json and package.json -- paths don't seem to work in the execMap for whatever reason.
Also, an even easier solution is to just not use any JSX in your main/server script, install node-jsx and then require your JSX files as needed.

Durandal.js optimizer generating empty main-built.js

I am trying to optimize my Durandal app but the main-built.js is blank.
I have tried running node r.js -o app.build.js and this threw an error saying that it could not find a file. I added these paths in my main.js file and each individual error went away. However, now the command above just exits with "Tracing dependencies for: durnadal/amd/almond.custom" and the file is still blank.
Question: Which libraries need to go into the paths below? It seems to the external libraries that I use in my index.html and it needs the exact file name?
require.config({
paths: {
"text": "durandal/amd/text",
"breeze": "lib/breeze/breeze.min",
"knockout": "lib/knockout/knockout.mapping-latest",
}
});
When I run Optimizer.exe in the Durandal AMD folder main-built.js is blank. This is the app.build.js file that is generated - any help appreciated on how to get more verbose logging with Almond. I have tried optimizer -verbose true with no luck.
{
"name": "durandal/amd/almond-custom",
"inlineText": true,
"stubModules": [
"durandal/amd/text"
],
"paths": {
"text": "durandal/amd/text"
},
"baseUrl": "C:\\DNNDev.me\\DesktopModules\\Framework.App\\App",
"mainConfigFile": "C:\\DNNDev.me\\DesktopModules\\Framework.App\\App\\main.js",
"include": [
"text!about.html",
"about",
"appNavigation",
"config",
"text!dareAdd.html",
"dareAdd",
"text!dareDetail.html",
"dareDetail",
"text!dareList.html",
"dareList",
"text!dareListItem.html",
"dataContext",
"dataService",
"dataServiceHelper",
"enums",
"errorWatcher",
"text!home.html",
"home",
"text!index.html",
"text!indextopcoat.html",
"indextopcoat",
"text!kendoIndex.html",
"text!loader.html",
"logger",
"text!login.html",
"login",
"main-built",
"main",
"text!menu.html",
"model",
"text!navbar.html",
"text!notifyOfError.html",
"notifyOfError",
"text!privacy.html",
"privacy",
"text!profile.html",
"profile",
"text!shell.html",
"shell",
"text!signup.html",
"signup",
"text!testpage.html",
"testpage",
"uiutilities",
"userState",
"viewModelHelper",
"text!walkthrough.html",
"walkthrough",
"widgetService",
"css/telerik/js/kendo.dataviz.min",
"css/topcoat/js/hello",
"css/topcoat/js/hello.min",
"css/topcoat/js/index",
"css/topcoat/lib/hello",
"css/topcoat/lib/vendor/ender.min",
"css/topcoat/lib/vendor/fastclick",
"durandal/app",
"durandal/composition",
"durandal/events",
"durandal/http",
"text!durandal/messageBox.html",
"durandal/messageBox",
"durandal/modalDialog",
"durandal/system",
"durandal/viewEngine",
"durandal/viewLocator",
"durandal/viewModel",
"durandal/viewModelBinder",
"durandal/widget",
"durandal/plugins/router",
"durandal/transitions/entrance",
"js/cordova",
"js/facebookscript",
"lib/bootstrap/bootstrap",
"lib/bootstrap/bootstrap.min",
"lib/breeze/breeze.debug",
"lib/breeze/breeze.intellisense",
"lib/breeze/breeze.min",
"lib/breeze/q",
"lib/breeze/q.min",
"lib/jquery/jquery-2.0.3.intellisense",
"lib/jquery/jquery-2.0.3",
"lib/jquery/jquery-2.0.3.min",
"lib/knockout/knockout-2.3.0.debug",
"lib/knockout/knockout-2.3.0",
"lib/knockout/knockout.mapping-latest.debug",
"lib/knockout/knockout.mapping-latest",
"lib/knockout/knockout.validation.debug",
"lib/knockout/knockout.validation",
"lib/moment/moment",
"lib/moment/moment.min",
"lib/ratchet/ratchet",
"lib/sammy/sammy-0.7.4",
"lib/sammy/sammy-0.7.4.min",
"lib/toastr/toastr",
"lib/toastr/toastr.min"
],
"exclude": [],
"keepBuildDir": true,
"optimize": "uglify2",
"out": "C:\\DNNDev.me\\DesktopModules\\Framework.App\\App\\main-built.js",
"pragmas": {
"build": true
},
"wrap": true,
"insertRequire": [
"main"
]
}
In your path you are setting your reference to knockout equal to the mapping plugin, which is no bueno.
As shown in this answer, Durandal.js optimizer not working (empty main-built.js) you can run it like Rainer shows and you should see a more specific error.
One thing that I found - if you remove a view model or use a folder or directory as a purgatory (about to be deleted) those files may not be used in your app but if they are in the file structure they will still be evaluated by the optimizer.
EDIT
Check here for more info on the optimizer - Tracking down optimizer issues in durandal.js
Also, are you building debug or release? Are you targeting the correct one? durandal optimizer references wrong path when building it as a post build process in Visual Studio
Also, if you are referencing Knockout.js, I think you mean to reference "lib/knockout/knockout-2.3.0" not the knockout mapping plugin.
Unless I am missing something you shouldn't have to add those paths to your main.js file. Breeze and Knockout should be referenced already. Depending on your project type, your editor, etc... it is probably bundled in your App.Start folder under DurandalBundleConfig. If it is not then are you just referencing the libraries from your index.html?
Move them into the bundle config if that is the case (something like this) -
bundles.Add(
new ScriptBundle("~/scripts/vendor")
.Include("~/Scripts/jquery-{version}.js")
.Include("~/Scripts/jquery-ui-{version}.min.js")
.Include("~/Scripts/knockout-{version}.js")
.Include("~/Scripts/sammy-{version}.js")
.Include("~/Scripts/bootstrap.min.js")
.Include("~/Scripts/knockout-bootstrap.min.js")
.Include("~/Scripts/Q.js")
.Include("~/Scripts/breeze.debug.js")
);
Note that you need to load Q prior to Breeze, as Breeze depends on Q.

Resources