jest hangs indefinitely, runs no tests - node.js

Every time I run jest it never runs anything. I have let the counter go arbitrarily high. I have run jest with --no-cache
jest --debug output is as follows:
{
"configs": [
{
"automock": false,
"browser": false,
"cache": true,
"cacheDirectory": "/var/folders/7v/64n1tsk11zs2pbwf5bm_c9kc0000gn/T/jest_dx",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"detectLeaks": false,
"forceCoverageMatch": [],
"globals": {},
"haste": {
"defaultPlatform": "ios",
"platforms": [
"android",
"ios",
"native"
],
"providesModuleNodeModules": [
"react-native"
]
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"js",
"json",
"jsx",
"node"
],
"moduleNameMapper": [
[
"^React$",
"/Users/skilurus/github/flock-react-app/node_modules/react"
]
],
"modulePathIgnorePatterns": [
"/Users/skilurus/github/flock-react-app/node_modules/react-native/Libraries/react-native/"
],
"name": "b29a126b130a0be47202d3bc7b00f1b4",
"resetMocks": false,
"resetModules": false,
"restoreMocks": false,
"rootDir": "/Users/skilurus/github/flock-react-app",
"roots": [
"/Users/skilurus/github/flock-react-app"
],
"runner": "jest-runner",
"setupFiles": [
"/Users/skilurus/github/flock-react-app/node_modules/regenerator-runtime/runtime.js",
"/Users/skilurus/github/flock-react-app/node_modules/react-native/jest/setup.js",
"/Users/skilurus/github/flock-react-app/test-setup.js"
],
"snapshotSerializers": [
"/Users/skilurus/github/flock-react-app/node_modules/enzyme-to-json/serializer.js"
],
"testEnvironment": "/Users/skilurus/github/flock-react-app/node_modules/jest-environment-jsdom/build/index.js",
"testEnvironmentOptions": {},
"testLocationInResults": false,
"testMatch": [
"**/__tests__/**/*.js?(x)",
"**/?(*.)(spec|test).js?(x)"
],
"testPathIgnorePatterns": [
"/node_modules/",
"e2e"
],
"testRegex": "",
"testRunner": "/Users/skilurus/github/flock-react-app/node_modules/jest-jasmine2/build/index.js",
"testURL": "about:blank",
"timers": "real",
"transform": [
[
"^.+\\.js$",
"/Users/skilurus/github/flock-react-app/node_modules/babel-jest/build/index.js"
],
[
"^[./a-zA-Z0-9$_-]+\\.(bmp|gif|jpg|jpeg|mp4|png|psd|svg|webp)$",
"/Users/skilurus/github/flock-react-app/node_modules/react-native/jest/assetFileTransformer.js"
]
],
"transformIgnorePatterns": [
"node_modules/(?!react-native|native-base|react-navigation|react-native-fabric|tipsi-stripe)"
],
"watchPathIgnorePatterns": []
}
],
"globalConfig": {
"bail": false,
"changedFilesWithAncestor": false,
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"coverageDirectory": "/Users/skilurus/github/flock-react-app/__coverage__",
"coverageReporters": [
"json",
"lcov",
"text"
],
"coverageThreshold": {
"global": {
"branches": 70,
"functions": 75,
"lines": 85,
"statements": 80
}
},
"detectLeaks": false,
"expand": false,
"globalSetup": null,
"globalTeardown": null,
"listTests": false,
"mapCoverage": false,
"maxWorkers": 7,
"noStackTrace": false,
"nonFlagArgs": [],
"notify": false,
"notifyMode": "always",
"passWithNoTests": false,
"rootDir": "/Users/skilurus/github/flock-react-app",
"runTestsByPath": false,
"testFailureExitCode": 1,
"testPathPattern": "",
"testResultsProcessor": null,
"updateSnapshot": "new",
"useStderr": false,
"verbose": true,
"watch": false,
"watchman": true
},
"version": "22.3.0"
}
node --version: 8.9.4
npm --version: 5.6.0
yarn --version 1.3.2
Has anybody seen anything similiar? Does anybody know hot to fix this?

This happens to me too but it's intermittent, very frustrating though. I have discovered a workaround which is to run using the --runInBand flag, which just runs tests in the same thread:
jest --runInBand

Run you tests like so:
jest --detectOpenHandles --forceExit
--detectOpenHandles logs out errors preventing your tests from exiting clearly and it implies --runInBand which ensures your tests run in the same threads so no overlapping.
--forceExit which terminates your tests if something is wrong instead of hanging.

For the record, in my case it turned out to be a caching problem (I tried many many other things before).
For jest >=22.0.0 use the --clearCache option to clear the cache.
For jest <22.0.0 use the --showConfig option, search for the cacheDirectory property and delete the mentioned directory.
Hope this helps someone.

On MacOS uninstalling and reinstalling watchman didn't work for me.
Running watchman version hangs indefinitely.
do this to fix the watchman from hanging:
launchctl unload ~/Library/LaunchAgents/com.github.facebook.watchman.plist
watchman version
https://github.com/facebook/watchman/issues/381#issuecomment-257673900
You should see something like this then you know it worked:
{
"version": "2021.08.23.00"
}
Then re-run your jest tests

On MacOS I fixed this by uninstalling and reinstalling watchman using brew uninstall watchman and then reinstalling with brew install watchman. I had recently upgraded the OS so that may have something to do with it.

I had a similar issue. Most of my test where running but one suite was continuously running and never erroring.
It turned out I had a race condition in one of my useEffects. Which just cause jest to continuously run.
To diagnose the issue:
Comment out all test but one. keep adding a test till you find the one triggering the error.
Analyze the test to Identify which code is effected. (My issue turned out to be in a UseEffect.)
Identify which state object is causing the race condition.
Fix: remove it or throw a condition check on your code to prevent the race condition

In my case it was because I was using a jest plugin for VS code and auto save was enabled. So, jest hanged after running too many times.
Removing the /tmp/jest_rs solved my problem.

So I had a situation similar to this, only that jest refused to run any of my tests! The cause was a little convoluted:
I hadn't run the project in over 6 months and various dependencies had picked up vulnerability issues.
Back when I had last run the project and tests, I had jest installed globally with a global config.
Then at one point, I had uninstalled jest from global (hence losing the global config) but didn't remember to add a local one to the project I'm talking about.
When debugging to try and get the tests to run, I nuked my node modules and did a fresh install.
Only after adding a jest.config with setting the no cache options did it eventually work out.
In summary:
If you don't have jest installed globally, make sure to have a jest config for your project.
After using the cli to set up the config, go back and manually check all the options you've chosen are there and modify the ones cli didn't prompt for.

I had the same issue, tests pass and then it hangs and the CI hangs too. I stumbled upon --forceExit, and it fixed it for me.

Debug useEffect hook used inside components because some times useEffect creates infinite loop problems and the jest doesn't finishes the tests

I have fixed this by modifying my .babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
[
"styled-jsx/babel",
{
// "plugins": ["styled-jsx-plugin-postcss"]
}
]
]
}

In my case I tried everything around internet and the only solution was to set isolatedModules: true (I explicitly set it to false).

In my case, updating nodejs from an older version (ie. 12.16.1) to something more recent (eg. 14.17.3) and then re-installing jest (npm install jest -g) resolved this completely.

I had something similar with the project on NestJS. It turned out that one of the modules contained an imported module, but it was not installed. And for some inexplicable reason, there was no information about this when the tests were launched.

check your tests, in my case I mistake and put an extra "a" on the test
test('test expected that ..', async (a) => {
...
this makes my test hang forever (using node 14.15 and jest 29.1.2).

The #rohit's answer has given me the clue to find the solution to my problem, my code was working fine, but jest was failing into an infinite loop with the useEffect
so I've solved making a mock of it
import React from 'react'
const mockUseEffect = jest.fn()
jest.spyOn(React, 'useEffect').mockImplementation(mockUseEffect)
you can adapt it as your needs

Related

Jest moduleNameMapper and NPM package exports

I am developing fullstack NPM packages with multiple entrypoints (namely client, server and sometimes tests), using the exports property of package.json.
I also use a small hack to make TS work with exports until it's officially supported (see this Stack Overflow post, this hackish solution and this ticket).
The package.json ends up looking like this:
{
"name": "#vulcanjs/graphql",
"version": "0.4.7",
"main": "./dist/index.js",
"files": [
"dist/"
],
"exports": {
".": "./dist/index.js",
"./server": "./dist/server/index.js",
"./testing": "./dist/testing.js"
},
"types": "./dist/index.d.ts",
"typesVersions": {
"*": {
"server": [
"./dist/server/index.d.ts"
],
"testing": [
"./dist/testing.d.ts"
]
}
},
"description": "Vulcan graphQL schema generator",
...
You can then import using either #vulcanjs/graphql for shared code, and #vulcanjs/graphql/server for Node.js-only code.
It works perfect in my Next.js app. However, it seems to break Jest moduleNameMapper.
First, I had this:
moduleNameMapper: {
"#vulcanjs/(.*)": [
"<rootDir>/node_modules/#vulcanjs/$1",
],
},
The error is:
Configuration error:
Could not locate module #vulcanjs/graphql/server mapped as:
[
"/code/vulcan-next/node_modules/#vulcanjs/graphql/server",
].
The problem is that it tries to find a package named #vulcanjs/graphql/server: yet "server" is not a different package, it's an entrypoint of #vulcanjs/graphql.
I've also tried this:
moduleNameMapper: {
"#vulcanjs/(.*)/(.*)": [
"<rootDir>/node_modules/#vulcanjs/$1",
],
},
With this config, #vulcanjs/graphql/server is mapped to #vulcanjs/graphql. The problem is that now, server code is not found. I've checked and the problem is that this solution totally removes the /server: so #vulcanjs/graphql/server points to the main entrypoints instead of the server entrypoint.
Finally I did try to remove the moduleNameMapper, but then #vulcanjs/graphql/server package is not found by Jest. Note that I need the mapper for a use case I did not demonstrate here, so getting rid of it is possible but not the best solution.
The bug can be reproduced by installing the framework: https://github.com/VulcanJS/vulcan-next. You can clone, yarn install, unskip the test in src/models/tests/sampleModel.server.test.ts and run yarn run test:unit sampleModel. It will show the error.
Any idea how I could fix this?

Unbound breakpoints in Docker node.js TypeScript application

There are a lot of questions on this topic, and I have tried many of the solutions that worked for others, but the solution seems to depend on several things such as the version of VS Code and the recipe used.
This is my VS Code Help>About info:
Version: 1.60.2 (user setup)
Commit: 7f6ab5485bbc008386c4386d08766667e155244e
Date: 2021-09-22T12:00:31.514Z
Electron: 13.1.8
Chrome: 91.0.4472.164
Node.js: 14.16.0
V8: 9.1.269.39-electron.0
OS: Windows_NT x64 10.0.17763
The OS is Windows 10.
The Docker plugin is installed.
I have Docker Desktop 2.3.0.3 installed.
The application is written in TypeScript with inversify IOC.
I am using the launch.json and tasks.json files in src/.vscode.
The Docker container is built with the contents of the workspacefolder in /app. It is running locally, using the VS Code Docker plugin.
launch.json:
{
"configurations": [
{
"name": "Docker Node.js Launch",
"type": "docker",
"request": "launch",
"port": 9229,
"protocol": "inspector",
"preLaunchTask": "docker-run: debug",
"localRoot": "${workspaceFolder}/",
"platform": "node",
"remoteRoot": "/app/",
"sourceMaps": true,
}
]
}
tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"type": "docker-build",
"label": "docker-build",
"platform": "node",
"dockerBuild": {
"dockerfile": "${workspaceFolder}/Dockerfile",
"context": "${workspaceFolder}",
"pull": true
}
},
{
"type": "docker-run",
"label": "docker-run: release",
"dependsOn": [
"docker-build"
],
"platform": "node"
},
{
"type": "docker-run",
"label": "docker-run: debug",
"dependsOn": [
"docker-build"
],
"dockerRun": {
"env": {
"DEBUG": "*",
"NODE_ENV": "development",
},
"command": "node --inspect-brk=0.0.0.0 dist/index.js",
"envFiles": [".env"],
},
"node": {
"enableDebugging": true,
"inspectPort": 9229
}
}
]
}
tsconfig.json:
{
"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"noImplicitAny": true,
"strictNullChecks": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"outDir": "./dist/",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"typeRoots": [ "./types", "./node_modules/#types"],
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "src/**/*.test.ts", "types", "**/tests/*.ts"]
}
When I initiate debug (select the Docker Node.js Launch option and hit F5), the docker builds and starts. The application stops on the first line of dist/index.js, but all my breakpoints (which are all in classes) show as unbound and the debugger does not stop on any of them. The application runs normally otherwise.
I assume that the breakpoints are unbound because VS Code can not map the running code back to the breakpoints in the source. But I have tried opening the files inside the container and setting breakpoints there, and that doesn't work either.
What do I have to do to make breakpoints work?
I had a similar issue today and was finally able to solve it. I will provide my findings here in the hope it might be helpful to you too.
1. Use trace
By setting trace: true in the launch.json configuration, you will get a lot of more details in your logs.
You can read how to make use of that here: NodeJs Debugging in Visual Studio Code
When starting the debugger config with trace: true, you will get a log entry in your debug console in the likes of
Verbose logs are written to:
/somepath/vscode-debugadapter-xxxxxx.json.gz
You can take this logfile and analyze it here in this interesting online tool by Microsoft: vscode-pwa-analyzer (Whole Project on Github)
There's a whole lot of logs in there. Probably best if you just try it out and see if you see anything helpful in there.
2. check your sourcemaps
For me it really helped to look at one of my sourcemap files. Go to your build / dist or whatever name you use for your build directory and look for a .map File.
If you open it, you should see something along the lines of
{"version":3,"file":"somefile.js","sourceRoot":"","sources":["../../../src/somedir/somefile.ts"] ... }
Make sure that the sources path is correct. Otherwise there might be something off with your tsconfig File.
3. check the outFiles config
This seemed to be necessary for me to configure to make it work. Add all the paths as glob patterns that contain compiled Javascript Files.
"outFiles": ["${workspaceFolder}/dist/**.js"],
4. sourceMapPathOverrides
There might also be an issue with the Source Map Paths. You can see if adding this snippet here helps:
"sourceMapPathOverrides": {
"webpack:///./*": "${workspaceRoot}/*",
},
5. check the program config
For me, adding the program config property finally did the trick.
If you don't know which one that might be, in my case it helped looking at what my Chrome used as the entry File.
Go to chrome://inspect in your Chrome Browser while your application is started and check what you see there.
In this example the entry File would be the server.js, which led me to configure the source of that file as the program, (with the local path) like so:
"program": "${workspaceFolder}/src/server.ts"
Conclusion
Your setup is probably different from mine and I still don't understand all the settings 100% to be honest. But maybe one of these things helps you get closer to find a solution. Let me know if it helped, and good luck.

How can I disable the code coverage folder that PhpStorm creates when tests are run?

With the latest version (currently 2021.1) of PhpStorm when running tests it adds a coverage folder to my src directory.
It appears to be a code coverage report for all files. Is there a way to stop it doing that?
I have never used it and often forget to add it to my .gitignore file and it often gets committed.
For us it is unnecessary.
EDIT 2021-06-03
As per LazyOne's comment below, it does seem to be jest.
I was unaware that it was a jest only issue as I don't use PHP at the moment (though still have the editor).
It only started happening on recent updates hence my confusion.
Setting the coverageDirectory to something different indeed moves the coverage folder.
Removing all coverage settings, and running a test with coverage still does create the folder.
Here is a screenshot of the folder that is being created looks like.
Jest config is currently
{
"globalSetup": "../jest.setup.ts",
"setupFilesAfterEnv": ["../jest.setupFiles.ts"],
"rootDir": "src",
"moduleFileExtensions": ["js", "json", "ts"],
"collectCoverage": true,
"collectCoverageFrom": [
"./**/*.{ts,js}",
"!./**/tests/**/*",
"!./**/mocks/**/*",
"!./**/routes.*",
"!./**/config/**/*",
"!./**/__tests__/**/*",
"!./**/__mocks__/**/*",
"!./**/test/**/*",
"!./**/exports.*",
"!./src/coverage"
],
"coverageReporters": ["text", "text-summary"],
"coverageDirectory": "../coverage",
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(js|ts)x?$",
"testPathIgnorePatterns": [],
"transform": {
"^.+\\.(ts)?$": "ts-jest"
}
}

Why does ESLint throw an error while using export/import statement on Node.js 12.13.0?

I have a project built on Node.js, DynamoDB and other AWS services, deployed on Serverless architecture. I also have the ESLint package installed.
I am getting the following error:
ESLint: Import and export declarations are not supported yet on Node 8.0.0. (node/no-unsupported-features)
Following are the details of my project:
Node version: 12.13.0
NPM version: 6.12.0
Serverless version: 1.40.0
ESLint: 6.8.0
I have double verified by node version of my project and my local. Both are the same (12.13.0).
I am able to use async/await but whenever I try using import/export, it gives me the error.
Following is my .eslintrc file :
{
"extends" : [
"eslint:recommended",
"plugin:node/recommended"
],
"plugins": [
"promise",
"node"
],
"env" : {
"browser" : false,
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module",
"impliedStrict": false
},
"globals" : {
},
"rules": {
"no-console": 0,
"no-unused-vars": ["error", { "vars": "all", "args": "none", "ignoreRestSiblings": false }],
"node/no-unpublished-require": [
"error",
{
"allowModules": [
"aws-sdk"
]
}
],
"node/no-unsupported-features": ["error", {
"version": 8,
"ignores": []
}]
}
}
`
Node.js by default uses Common.js style for import/export.
In the new versions of Node.js you can use different extensions or the --experimental-modules option in the command line.
*.mjs you use ES6 import/export
*.js or *.cjs you use commonjs
If you consider that ECMAScript modules import/export are still experimental, I would say that ESLint is quite correct.
You might want to override EsLint rules in order to make it work with that.
Firstly consider that the rule you mentioned is obsolete so you might want to use the new ones => https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-unsupported-features.md
Because those rules are obsolete I would suggest you to take a look at your eslint and its external rulesets version (if you use them) and try again.
In any case...
Check/create the .eslintrc.json file in the root of your project and override the project rules you might want to change.
Just stumpled upon a similiar error.
In my case i solved it by adding the engines definition to package.json
"engines": {
"node": ">=12.13.0"
}
I am not sure if this solves you problem but a quite similar issue can be found here.

How to correctly build an electron nodejs program into an .exe?

I'm using Electron v2.0.8, Node v8.9.3, npm 6.4.1. I've created a simple "Hello world" program using html, css, js alongwith npm.
The program works really fine when I cd to the program directory and npm start. But when it is build(packaged) using, electron-packager <sourcedir> <appname> --platform="win32", the "sweetalert" is not showing its message, which did show when using npm start. But the buttons function as supposed. ("Clears the text field")
I suspect this has something to do with the file paths or something, but being new to this whole framework, I have no clue.
I don't know whether my whole "creating an .exe approach" is 100% correct or not. I've tried with electron-forge but it gave so many errors so I gave up on it and switched to electron-packager instead. None of the online helps work for me(I believe due to different versions) Someone please help.
For anyone else facing a similiar issue. Actually my program was built correctly and there was no error in the code.
What had happened was that the file paths were not correctly configured. When I manually copied the necessary files for the "sweetalert" to run, it showed up the message. Thus no errors specific to sweetalert.
I'll have to find a way to solve the 'path' issue anyways.
UPDATE:
Adding the code
"extraFiles": [
"folder_to_be_included_in_build"
],
into the package.json file now copies the needed folder during "building" the app. Now no need to copy the folder manually to the build.
package.json etc...
"repository": {
"url": "https://github.com/your/repo.git",
"type": "git"
},
"author": {
"name": "Author name"
},
"main": "./afolder/main.js",
"build": {
"productName": "The product name",
"compression": "maximum",
"files": [
"./afolder",
"./node_modules",
"./package.json"
],
"appId": "any.id.app",
"asar": true,
"win": {
"icon": "./your/icon/path/icon.ico",
"target": "nsis"
},
"nsis": {
"oneClick": false,
"installerIcon": "./afolder/your/icon/path/icon.ico",
"uninstallerIcon": "./afolder/your/icon/path/icon.ico",
"perMachine": false,
"deleteAppDataOnUninstall": true,
"artifactName": "${productName} ${os} ${arch} v${version} setup.exe",
"allowToChangeInstallationDirectory": true,
"createDesktopShortcut": true,
"createStartMenuShortcut": true,
"shortcutName": "ShortcutName"
},
"asarUnpack": [
//remove this comment ...
//packages you want to include after install.
//for e.g.
"./node_modules/electron-window-state",
"./node_modules/fs-extra",
"./node_modules/7zip-bin"
],
"npmRebuild": false,
"nodeGypRebuild": false,
"directories": {
"output": "../installer/${productName} v${version} setup"
}
},
"scripts": {
"start": "electron .",
"installer": "yarn build --x64"
},
package.json etc...
You will need "npm install electron-builder yarn --save-dev"
Amend your package.json file with the above content (change productName etc... to your custom needs)
npm run installer
you should see a folder called installer generated on the parent directory

Resources