jest#23.1.0 collectCoverageFrom not picking the files outside root directory - jestjs

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

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

Webpack file-loader with sass-loader

I am new to nodejs and get a problem when trying to use sass with it.
The following information is just fictional, but it represents the
actual condition.
THE SCENARIO:
I have the following folder structure:
frontend/
- scss/
- style.scss
- main.js
webpack.config.js
Goal:
I want to compile the style.scss to style.css using webpack and put it inside dist/frontend/css/ directory, so it should be resulting this path: dist/frontend/css/style.css and create the following folder structure:
dist/
- frontend/
- scss/
- style.scs
- main.js
frontend/
- scss/
- style.scss
- main.js
webpack.config.js
THE CODES:
main.js
import `style from "./scss/style.scss";`
webpack.config.js
module.exports = {
mode: "development",
entry: {
main: "./frontend/main.js"
},
output: {
path: path.join(__dirname, "/dist/frontend"),
publicPath: "/",
filename: "[name].js"
},
module: {
rules: [
{
test: /\.(s*)css$/,
use: [
{
loader: "file-loader",
options: {
name: "css/[name].[ext]"
}
},
"style-loader/url",
"css-loader?-url",
"sass-loader"
]
}
]
}
THE RESULT:
I get this message:
Module not found: Error: Can't resolve './scss/style.scss' in 'E:\project_name\frontend'
THE QUESTIONS
Why is that happening?
What is the correct codes to achieve the Goal?
As the message said, this path is not valid: './scss/style.scss'. There are typo when defining the path. The folder is supposed to be sass instead of scss.
The following configuration will work to achieve the Goal mentioned in the question:
module: {
rules: [
{
test: /\.(s*)css$/,
use: [
"style-loader/url",
{
loader: "file-loader",
options: {
name: "css/[name].css"
}
},
"sass-loader"
]
}
]
}
It works like Mini CSS Extract Plugin, but does not generating additional .js files for each .css file when used to convert multiple .scss files into different .css files.

Jest Is Not Transpiling ES6 Modules In Test (SyntaxError: Unexpected token export)

I'm at a boiling point with getting Jest to understand ES6 modules import/export syntax and it is hindering my project development progress. My project structure is the following:
root module
org-domain (ES6)
org-services (ES6)
react-ui-module (React via CRA2)
org-services has a local path dependency on org-domain in its package json:
// in org-services package.json
"dependencies": {
"#org/domain": "file:../org-domain",
},
My .babelrc in org-services is the following:
{
"env": {
"test": {
"presets": ["#babel/preset-flow", "#babel/preset-env"]
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
},
"presets": [
"#babel/preset-flow",
["#babel/preset-env", {
"targets": {
"esmodules": true
}
}]
],
"plugins": [
["module-resolver", {
"root": ["./node_modules/#org/domain"],
"alias": {
"#org/constants": "./node_modules/#org/domain/src/constants",
"#org/contracts": "./node_modules/#org/domain/src/request-contracts"
}
}]
]
}
I do not know if the problem is due to how I am including my dependencies so I'm going to add the finer details of anything related to my import/export of these modules for the sake of clarity.
In the implementation files of org-services I am importing org-domain using npm scoped syntax like so: import ... from '#org/domain
Here are some observations I have:
In local development, when I try to reference click #org/domain, instead of being directed to org-services/node_modules/#org/domain I get redirected to the actual relative directory location which is root/org-services. I believe Jest ignores node_modules (correct me if I am wrong) but in my jest.config.js for org-services, I have:
collectCoverage: true,
coverageDirectory: 'coverage',
coveragePathIgnorePatterns: [
'/node_modules/'
],
moduleDirectories: [
'src',
'node_modules'
],
moduleFileExtensions: [
'js'
],
transform: {
'^.+\\.js$': 'babel-jest'
},
transformIgnorePatterns: [
'node_modules/(?!#org/domain)$'
]
To my understanding, everything should just work right now with all the configuration I have with respect to setting the plugin #babel/plugin-transform-modules-commonjs in test (within .babelrc) and including the '^.+\\.js$': 'babel-jest' instruction under the transform key in jest.config.js located under org-services -- but it does not.
I have tried every single thing I could find online with respect to this issue with no success. I have not gotten anywhere since and my patience is lost with this testing framework and the lack of support for ES6. It should not be this hard, so clearly I am doing something wrong here. Please advise.
Update 1
Found another SO post that is a mirror of this situation I am in.
Jest fails to transpile import from npm linked module
Unfortunately, the provided solution does not work for my case.
After upgrading from #babel/xyz: 7.0.0 to 7.1.2 I started getting an error regarding "import"
Jest encountered an unexpected token
<snip>
Details:
C:\....\SstcStrategy.test.js:2
import sequelizeFixtures from 'sequelize-fixtures';
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
To fix this I had to add #babel/plugin-transform-modules-commonjs as you mention in your question.
My babel.config.js now looks like this:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: '8.10',
},
debug: false,
},
],
],
ignore: ['node_modules'],
plugins: [
'#babel/plugin-transform-runtime',
'#babel/plugin-transform-modules-commonjs',
// Stage 2
['#babel/plugin-proposal-decorators', { legacy: true }],
'#babel/plugin-proposal-function-sent',
'#babel/plugin-proposal-export-namespace-from',
'#babel/plugin-proposal-numeric-separator',
'#babel/plugin-proposal-throw-expressions',
// Stage 3
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-syntax-import-meta',
['#babel/plugin-proposal-class-properties', { loose: false }],
'#babel/plugin-proposal-json-strings',
],
};
Also BTW you don't need to define babel-jest transform in jest.config.js as this is the default setting.
Hope this helps

Jest gives `Cannot find module` when importing components with absolute paths

Receiving the following error when running Jest
Cannot find module 'src/views/app' from 'index.jsx'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object.<anonymous> (src/index.jsx:4:12)
index.jsx
import AppContainer from 'src/views/app';
package.json
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleDirectories": [
"node_modules",
"src"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
},
My tests that run files that only contain relative paths in the tree run correctly.
To Clarify, I'm looking for how to configure Jest to not fail on absolute paths.
I think you're looking for: roots or modulePaths and moduleDirectories
You can add both relative and absolute paths.
I would make sure to include <rootDir> in the roots array, <rootDir> in the modulePaths array, and node_modules in the moduleDirectories array, unless you've got a good reason to exclude them.
"jest": {
"roots": [
"<rootDir>",
"/home/some/path/"
],
"modulePaths": [
"<rootDir>",
"/home/some/other/path"
],
"moduleDirectories": [
"node_modules"
],
}
Since in package.json you have:
"moduleDirectories": [
"node_modules",
"src"
]
Which says that each module you import will be looked into node_modules first and if not found will be looked into src directory.
Since it's looking into src directory you should use:
import AppContainer from 'views/app';
Please note that this path is absolute to the src directory, you do not have to navigate to locate it as relative path.
OR you can configure your root directory in moduleDirectories inside your pakcage.json so that all your components could be imported as you want it.
Adding
"moduleDirectories": [
"node_modules",
"src"
]
should work if you have Jest's config in your package.json file.
If you have a jest.config.js file, you should add it there, otherwise package.json will be overriden (and ignored) by this config file. So in your jest.config.js file:
module.exports = {
// ... lots of props
moduleDirectories: ["node_modules", "src"],
// ...
}
That's because jest doesn't recognize relative imports like src/views/app
Add a rootDir and a modulePaths in package.json
"name": "my-app",
...
"jest": {
...
"rootDir": "./",
"modulePaths": [
"<rootDir>"
],
...
}
}
Make sure you have run npm i or npm install after update the package.json. My issue was that :0
For those who are building something from scratch with Webpack and Babbel.
Try the following steps:
Delete the node_modules folder and install again. (This was something that solved my issue).
Here is a link with the necessary documentation to set up Webpack which in some cases will not be necessary. Jest Docs Webpack
Here is a link to the docs that explains how to set up Jest with React (Without using Create-React-App). Jest React Docs
4. Here is an example with a simple setup with Jest. You can set this up in package.json or the Jest configuration file.
Disclaimer: This does not answer the OP question. But most people will end up here for the keywords used for this issue.
"jest": {
"moduleFileExtensions": ["js", "jsx"],
"moduleDirectories": ["node_modules"],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
},
In my case, I was running integration tests and all tests were in the same file with the path src/int-test.spec.ts in order to read paths I had to write:
"jest": {
...,
"moduleNameMapper": {
"src/(.*)": "<rootDir>/$1"
}
}
Adding __esModule:true fixed this issue for me.
jest.mock('module',()=>({
__esModule: true, // this makes it work
default: jest.fn()
}));
Hope this helps somebody. Although this is not very specific to the question.
This can also be caused by absolute imports present in the globalSetup file (or any files it references).
It seems like moduleNameMappers do not get applied to globalSetup files. I fixed this by just switching to relative imports for those specific files.
This Workaround:
Using "moduleNameMapper" in your jest configuration will make test-resolve work as expected:
"jest": {
"moduleNameMapper": {
"#(.*)": "<rootDir>/node_modules/$1"
}
}
https://gist.github.com/lydell/d62ce96c95c035811133a5396195da14
One of the modules I wanted to use has a .cjs extension.
Adding .cjs to moduleFileExtensions in jest.config.js fixed this problem for me.
My jest.config.js as example:
module.exports = {
moduleNameMapper: {
// see: https://github.com/kulshekhar/ts-jest/issues/414#issuecomment-517944368
"^#/(.*)$": "<rootDir>/src/$1",
},
preset: "ts-jest/presets/default-esm",
globals: {
"ts-jest": {
useESM: true,
},
},
testEnvironment: 'jsdom',
transform: {
'^.+\\.vue$': 'vue3-jest',
},
moduleFileExtensions: ['json', 'js', 'jsx', 'ts', 'tsx', 'vue', "cjs"],
moduleDirectories: ["node_modules"],
};
Just add "modulePaths" to your package.json
"jest": {
...
"modulePaths": [
"<rootDir>"
],
...
}
}
I had jest-expo installed, but not jest. Probably related that I'm prebuild-ejected from Expo. I had to run yarn add jest-expo jest to install jest, and updated jest-expo. Now my tests run.
Depending on your setup it might be, npm i jest-expo jest or expo install jest-expo jest. ... Got the idea from their docs https://docs.expo.dev/guides/testing-with-jest/

Resources