No tests found on running jest with grunt - javascript

I am trying to run my jest with a grunt task but on doing so I get No tests found message in console. Here is the setup for the same:
gruntfile.js snippet :
exec: {
jest: 'node node_modules/jest/bin/jest -u --config="test/unit/jest/jest.conf.json"'
}
jest.conf.json :
{
"testEnvironment": "jsdom",
"setupTestFrameworkScriptFile": "./enzyme.setup.js",
"testResultsProcessor": "jest-teamcity-reporter"
}
enzyme.setup.js :
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15.4';
configure({ adapter: new Adapter() });
Console on running the grunt exec task shows below:
No tests found
In C:\Vishal\UI\Jest-Grunt\proj\test\unit\jest
3 files checked.
testMatch: .js?(x),**/?(*.)(spec|test).js?(x) - 0 matches
testPathIgnorePatterns: \\node_modules\\ - 3 matches
Pattern: - 0 matches
Done, without errors.
However the surprising thing is if I don't pass the jest config file path in cli inside grunt exec task and instead specify the jest configuration in package.json file then it works.
Not sure why this is behaving like this.

Aah, after banging my head around. I noticed that the error is pity straight forward:
In C:\My-User\UI\Jest-Grunt\proj\test\unit\jest
This clearly explains that JEST tries to execute test cases inside folder specified above. But ideally JEST looks into __tests__. Hence I had to specify the roots folder myself. With package json this doesn't occur. Strange though!
Here is my updates jest configuration:
{
"testEnvironment": "jsdom",
"setupTestFrameworkScriptFile": "./enzyme.setup.js",
"testResultsProcessor": "jest-teamcity-reporter",
"coverageReporters": [
"teamcity", "lcov"
],
"roots": [
"../../../__tests__"
]
}

Related

Jest cannot find tests when tests are located under `node_modules` directory

After I performed refactoring on my project, I found that Jest could not find any test modules. It reported following error.
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
No files found in /home/.../node_modules/.../... /api.
Make sure Jest's configuration does not exclude this directory.
To set up Jest, make sure a package.json file exists.
Jest Documentation: https://jestjs.io/docs/configuration
Pattern: - 0 matches
After I examined a while, I found the smallest reproducible example is following :
node_modules/foo.js
function foo() {
return 'hello';
}
module.exports.foo = foo;
node_modules/foo.test.js
test( 'foo' , ()=>{
console.error( require('./foo.js' ).foo() );
});
And if foo.js and foo.test.js are moved out from node_modules directory, Jest works as normal.
In order to avoid long relative package names, I put all files under node_modules directory. If possible, I don't want to relocate them.
Is there any workaround or, if possible, any permanent proper solution for the issue?
Edited)
Why do you want to put those in node_modules ?
See Document src/node_modules as official solution for absolute imports
This is a known bug and the bug was already fixed.
A quick fix is creating jest.config.js in the root directory of your project tree as following :
const config = {
"testEnvironment": "node",
"testPathIgnorePatterns": [],
"haste": {
"retainAllFiles": true
}
};
module.exports = config;
Or you can add following in the package.json :
"jest": {
"testEnvironment": "node",
"testPathIgnorePatterns": [],
"haste" : {
"retainAllFiles": true
}
}
This answer is a sort of my reminder; hoping this saves a couple of precious hours of my friends.
Jest not running tests in src/node_modules #2145 (Jest)
Enable src/node_modules #1081 (Create React App)
Bug: Unable to run a test from whitelisted "node_modules" #11781
fix: Allow searching for tests in node_modules #11084 (Jest)

Jest fails when rendering React component with 'No element indexed by'

I am attempting to get Jest working for my React Native project and have run into a variety of problems, the most confusing of which is the following:
When I run any test that renders a component, it spits out the error No element indexed by 7.
Here is the full stack trace:
FAIL __tests__/App-test.tsx
● Test suite failed to run
No element indexed by 7
at ArraySet_at [as at] (node_modules/source-map-support/node_modules/source-map/lib/array-set.js:109:9)
at BasicSourceMapConsumer.SourceMapConsumer_originalPositionFor [as originalPositionFor] (node_modules/source-map-support/node_modules/source-map/lib/source-map-consumer.js:673:30)
at mapSourcePosition (node_modules/source-map-support/source-map-support.js:244:42)
at wrapCallSite (node_modules/source-map-support/source-map-support.js:397:20)
at Function.prepareStackTrace (node_modules/source-map-support/source-map-support.js:446:39)
at Function.write (node_modules/#jest/console/build/BufferedConsole.js:101:7)
at console._log (node_modules/#jest/console/build/BufferedConsole.js:117:21)
at console.error (node_modules/#jest/console/build/BufferedConsole.js:161:10)
This same error occurs with any component I attempt to render.
Regarding this issue which purports to solve a similar problem, I have tried installing babel (npm install --save-dev babel-jest #babel/core #babel/preset-env) and setting "coverageProvider" in the jest config to "v8". With or without the v8 preset I am still getting the same errors. It's definitely possible that I configured something else wrong. Here are some code snippets which may be of use:
App-test.tsx
/**
* #format
*/
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
package.json
// ...
"jest": {
"preset": "react-native",
"coverageProvider": "babel",
"transformIgnorePatterns": [
"node_modules/(?!(react-native|#react-native|react-native-video|react-native-reanimated|#miblanchard/react-native-slider|react-native-gesture-handler)/)"
],
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
}
babel.config.js
module.exports = {
presets: [
'module:metro-react-native-babel-preset',
['#babel/preset-typescript', {allowDeclareFields: true}],
],
plugins: [
"react-native-reanimated/plugin",
],
};
As an additional note, I have tried adding #babel/preset-env to the list of babel presets, but this only resulted in a different error related to a separate package added to the transformIgnorePatterns list. Adding source-map-support to said list also solves nothing.
Edited to note that these tests fail regardless of whether or not the --coverage argument is applied
In the end, I solved my error by uninstalling node_modules, re-running npm install --save-dev babel-jest #babel/core #babel/preset-env and adding
"setupFiles": [
"./node_modules/react-native-gesture-handler/jestSetup.js",
// ...
]
to my package.json

Why Jest failing on node-fetch giving syntax error on import

I'm trying to understand how to fix the following error using Jest in my unit tests in NodeJS.
The test run with this command "test": "NODE_ENV=test jest spec/* -i --coverage --passWithNoTests",
I'm also using babel and this is my config
{
"presets": [["#babel/env", { "targets": { "node": "current" } }]],
"plugins": [
"#babel/plugin-syntax-dynamic-import",
["babel-plugin-inline-import", { "extensions": [".gql"] }],
["#babel/plugin-proposal-decorators", { "legacy": true }]
]
}
In package.json I have this
"jest": {
"verbose": true,
"collectCoverageFrom": [
"spec/**/*.js"
]
},
I tried several guides online but cannot find a solution to this
You've got Jest successfully configured to transform your code, but it is not transforming modules that you're importing—in this case node-fetch, which has the import keyword in its source code (as seen in your error). This is because, by default, Jest is configured not to transform files in node_modules:
transformIgnorePatterns [array]
Default: ["/node_modules/", "\.pnp\.[^\/]+$"]
An array of regexp pattern strings that are matched against all source file paths before transformation. If the file path matches any of the patterns, it will not be transformed.
You can set transformIgnorePatterns to exclude certain packages in node_modules with a jest.config.js like this:
const esModules = [
'node-fetch',
'data-uri-to-buffer',
'fetch-blob',
'formdata-polyfill',
].join('|');
module.exports = {
transformIgnorePatterns: [
`/node_modules/(?!${esModules})`,
'\\.pnp\\.[^\\/]+$',
],
};
(see https://github.com/nrwl/nx/issues/812#issuecomment-429420861)
If you have .babelrc try to rename it to babel.config.js
Source:
https://babeljs.io/docs/en/configuration#whats-your-use-case
but also this (there's more in the discussion)
Jest won't transform the module - SyntaxError: Cannot use import statement outside a module

Jest coverage tools fail

During in my react-native project, during test execution, Jest shows coverage and creates coverage reports.
Jest config:
import type {Config} from '#jest/types';
const config: Config.InitialOptions = {
// basic params to setup test ext and env
preset: '#testing-library/react-native',
verbose: true,
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
roots: [
'<rootDir>'
],
// tests coverage
collectCoverage: true,
coverageDirectory: "__tests__/coverage",
coverageReporters: [
'lcov',
'text',
],
collectCoverageFrom: [
"**/src/**/*.{js,jsx,ts,tsx}",
"!**/src/parameters/**/*.{js,jsx,ts,tsx}",
"!**/src/types/**/*.{js,jsx,ts,tsx}",
"!**/src/navigationRoots/**/*.{js,jsx,ts,tsx}",
"!**/node_modules/**",
],
coverageThreshold: {
global: {
lines: 70,
statements: 70
}
},
// additional
testRegex: "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
transform: {
'^.+\\.(js|ts|tsx)$': 'babel-jest'
},
transformIgnorePatterns: [
"node_modules/(?!(jest-)?#react-native|react-native|react-(native|universal|navigation)-(.*)" +
"|#react-native-community/(.*)" +
"|#react-navigation/(.*)" +
"|bs-platform" +
"|(#[a-zA-Z]+/)?(bs|reason|rescript)-(.*)+)"
],
};
export default config;
During testing I get errors:
Consider using the "jsdom" test environment.
ReferenceError: document is not defined
Consider using the "jsdom" test environment.
ReferenceError: window is not defined
in files which are generated during creation of coverage folder:
coverage/lcov-report/sorter.js
coverage/lcov-report/block-navigation.js
So, in jest documentation we see that we can specify jsdom environment in file which produces error like:
/**
* #jest-environment jsdom
*/
Ok, but here we have auto-generated files, not my test-files. How else can I fix these errors?
UPD: these errors does not appear if I delete coverage folder with all files before launching tests.so Jest creates everything good. But when I launch tests with existing "coverage" folder, during update shows errors
found answer on my question. when you specify jest tests folder as folder to place coverage report there, Jest considers, that coverage folder contains test.on first start when coverage folder does not exist it creates it without problems, but when you repeat coverage command, jest tries to test every js file in it. so coverage folder is needed to be excluded as test location for jest. how to do this you can find here

Jest can't resolve import with # (at) character

I have a problem. When I run Jest tests it can't resolve my imports with at (#) signs. I have an error:
FAIL src/App.test.js
● Test suite failed to run
Cannot find module '#/helpers/configureStore' from 'App.js'
How do I resolve this error?
I found the solution in this post. So according to the jest docs we should go to our package.json file, and make sure our config contains something like:
{
"jest": {
"moduleNameMapper": {
"#/(.*)$": "<rootDir>/src/$1"
}
}
}
"#/(.*)$": "<rootDir>/src/$1" that's a cool regex which will resolve our #/helpers/configureStore to src/helpers/configureStore.
Also remember to quit from jest interactive mode (with q key) and run it again to see changes.
If you are using a jest.config.ts and importing something like '#app/app.constants' you can replace
moduleNameMapper: {},
with
moduleNameMapper: {
"#app/(.*)$": "<rootDir>/src/app/$1",
},

Categories