Jest coverage tools fail - javascript

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

Related

Why does jest throw an ERR_UNKNOWN_FILE_EXTENSION when trying to use a ts file as custom testEnvironment?

I'm switching my TypeScript project to a (pnpm) monorepo and have troubles getting tests to run properly. I have a jest.config.js that uses a custom testEnvironment that's written in TypeScript as well. However, ever since I moved the specific project into my packages directory for the monorepo restructuring, jest throws an Error and doesn't run any tests:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\workspaces\repos\the-monorepo\packages\testproject\source\testtools\jsdom-environment-global.spec.ts
I tried it with #swc/jest as well as with ts-jest, had a look at How to use TypeScript in a Custom Test Environment file in Jest? (which makes me think "why did this ever work?") and, for whatever reason, it worked fine yesterday. I cleaned jest cache and reinstalled all node_modules to no avail. I also found answers related to "type": "module" in package.json, but this doesn't apply to my package. It's not an ESM.
Here's how the jest.config.js looks like:
/** #type {import('#jest/types').Config.InitialOptions} */
const config = {
silent: true,
testEnvironment: "<rootDir>/source/testtools/jsdom-environment-global.spec.ts",
roots: [
"<rootDir>/source"
],
maxWorkers: "50%",
transform: {
"^.+\\.(t|j)s$": ["#swc/jest", {
sourceMaps: "inline",
module: {
strict: false,
strictMode: false
},
jsc: {
target: "es2021",
parser: {
syntax: "typescript",
dynamicImport: true
}
}
}]
},
transformIgnorePatterns: [
"node_modules"
],
testMatch: [
"**/*/*.spec.ts",
"**/*/*.test.ts",
"!**/playwright-tests/**",
"!**/playwright-tests-smoke/**"
],
moduleFileExtensions: ["ts", "js", "node", "json"],
reporters: [
"default"
],
globals: {
self: {},
navigator: {},
jasmine: {},
__UNIT__: true
},
coverageDirectory: "test-results",
collectCoverage: false,
collectCoverageFrom: [
"./source/**/*.ts"
],
coveragePathIgnorePatterns: [
"/\\.spec\\.ts$/i",
"/.*node_modules.*/",
"/.*testtools.*/"
],
coverageReporters: [
"lcov", "cobertura"
],
coverageProvider: "v8",
resetMocks: true,
restoreMocks: true,
resetModules: true,
setupFilesAfterEnv: [
"jest-extended/all",
"<rootDir>/source/testtools/setup.spec.ts"
],
testPathIgnorePatterns: [
"<rootDir>/source/testtools/",
"<rootDir>/source/smoke-tests/",
"<rootDir>/source/performance-tests/",
"<rooDir>/source/playwright-tests/",
"<rooDir>/source/playwright-tests-smoke/"
],
moduleNameMapper: {
"^#test-helpers": "<rootDir>/source/testtools/index.spec.ts",
"^#test-tools/(.*)": "<rootDir>/source/testtools/$1",
'^(\\.{1,2}/.*)\\.js$': '$1'
}
};
module.exports = config;
Why is jest not able to parse the testEnvironment if it's a TypeScript file?
I found the issue: there seems to be some confusion around the transformer not being applied to ESM files. In my case, the jsdom-environment-global.spec.ts imported an ESM module from a different package within my monorepo. This import triggers an exception because jest tries to import it via require(), which is caught and then again imported via dynamic imports. This dynamic import then throws the exception that ts is an unknown exception. I'm not sure why these files haven't been transformed, but as of How to use TypeScript in a Custom Test Environment file in Jest? this seems to be normal.
Bottom line: don't import from ESM files within your jest testEnvironment module.

Jest config is not correctly recognizing the files to test upon

I have the current folder structure (where test is in the root of my directory):
test
unit
helper
helper.js
helper2
helper2.js
My jest.config.js looks like the following (this config file is in the root of my folder):
module.exports = {
testEnvironment: 'node',
collectCoverage: true,
collectCoverageFrom: ['**/*.{js,jsx}', '!**/node_modules/**'],
coverageDirectory: './coverage',
roots: ['<rootDir>/test'],
coverageReporters: ['text'],
rootDir: '.',
reporters: ['default'],
};
When I run the command: jest --verbose I am getting the error that No tests found, existing with code 1. Is there something wrong in my jest config that I need to modify?
Even that you've modified the roots jest still has testMatch. By default it's value is
"testMatch": [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[tj]s?(x)"
],
so you can change it to:
"testMatch": [
"**/*.[jt]s?(x)",
],
Note: by running jest --showConfig you'll get a nice overview of all of the configurations and an idea of what else might need to be changed

No tests found on running jest with grunt

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__"
]
}

JS : karma rollup empty bundle

[UPDATE]
The original title of this post was : "Bad karma, lost data" and standed for the mind word play, much more for the rimes than for a real fact. So I decided to alter it, for the sake of correctness and courtesy.
[UPDATE]
Hi there, I've a very classical program directory strcture:
dist/
karam.conf.js
node_modules/
package.json
rollup.config.js
src/
fp/
list.js # imports maybe.js
matbe.js
test/
fp/
list.specs.js
maybe.specs.js
I'm trying to preprocess the tests with rollup. My karma.conf.js is just like :
# karma.conf.js
const buble = require('#rollup/plugin-buble')
const resolve = require('#rollup/plugin-node-resolve').default
// console.log({ resolve })
module.exports = function(config) {
config.set({
basePath : '',
files: [
{
pattern: 'src/fp/*.js', watched: true
},{
pattern: 'test/fp/*.specs.js', watched: true
}
],
watch: true,
preprocessors: {
'src/fp/*.js': ['rollup2'],
'test/fp/*.specs.js': ['rollup2']
},
rollup2Preprocessor: {
output: {
name: 'fptest',
format: 'iife'
},
plugins: [
buble(),
resolve()
]
}
});
}
When I start karma, with npm or from CLI with "karma start --log-level debug", I get 4 empty bundles and get the error message "Error during file loading or preprocessing
TypeError: output is not iterable".
So I could not test my program properly.
What's happening and how to fix that ?
Thanks for replies, Regards.
Looking at your module loader, I suggest using a karma plugin like karma-rollup-preprocessor to bundle your module before running tests. This will bundle and wire-up your modules properly for testing.
And you don't need to specify all your files under files array.
files: [
'test/**/*.js'
],

"No ESLint configuration found" error

Recently, we've upgraded to ESLint 3.0.0 and started to receive the following message running the grunt eslint task:
> $ grunt eslint
Running "eslint:files" (eslint) task
Warning: No ESLint configuration found. Use --force to continue.
Here is the grunt-eslint configuration:
var lintTargets = [
"<%= app.src %>/**/*/!(*test|swfobject)+(.js)",
"test/e2e/**/*/*.js",
"!test/e2e/db/models/*.js"
];
module.exports.tasks = {
eslint: {
files: {
options: {
config: 'eslint.json',
fix: true,
rulesdir: ['eslint_rules']
},
src: lintTargets
}
}
};
What should we do to fix the error?
The error you are facing is because your configuration is not present.
To configure the eslint type
eslint --init
then configure as your requirement.
then execute the project again.
I've had the same error. It seems to need configuration.
Go to your project root & run in terminal
./node_modules/.bin/eslint --init
Try to swap config with configFile. Then :
Create eslint.json file and
Point the right location of it (relative to Gruntfile.js file)
Place some configuration in that file (eslint.json), i.e.:
.
{
"rules": {
"eqeqeq": "off",
"curly": "warn",
"quotes": ["warn", "double"]
}
}
for more examples, go here.
I hade the same problem with Gulp and running "gulp-eslint": "^3.0.1" version.
I had to rename config: to configFile in Gulp task
.pipe(lint({configFile: 'eslint.json'}))
For those having the same problem, this is how we've fixed it.
Following the Requiring Configuration to Run migration procedure, we had to rename eslint.json to .eslintrc.json which is one of the default ESLint config file names now.
We've also removed the config grunt-eslint option.
Create a new file on the root directory called .eslintrc.json file:
{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"semi": "error"
}
}
Just follow the steps
1.create eslint config file name eslintrc.json
2.place the code as given below
gulp.src(jsFiles)
// eslint() attaches the lint output to the "eslint" property
// of the file object so it can be used by other modules.
.pipe(eslint({configFile: 'eslintrc.json'}))
// eslint.format() outputs the lint results to the console.
// Alternatively use eslint.formatEach() (see Docs).
.pipe(eslint.format())
// To have the process exit with an error code (1) on
// lint error, return the stream and pipe to failAfterError last.
.pipe(eslint.failAfterError());
Webpack
I had eslint.rc file in my root project directory but event though
I was getting error.
Solution was to add exclude property to "eslint-loader" rule config:
module.exports = {
// ...
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
// eslint options (if necessary)
}
},
],
},
// ...
}
We faced this problem today and realized, that the issue was not caused inside the project that we were working on, but inside a package that we had a link on using the command:
yarn link
Which is a feature often useful to test out new features or when trying to debug an issue in a package that manifests itself in another project.
We solved it by either removing the link, or in case of ember.js disabling the developer mode of our addon package.
index.js
module.exports = {
isDevelopingAddon: function() {
return false;
},
...
}
gulp.task('eslint',function(){
return gulp.src(['src/*.js'])
.pipe(eslint())
.pipe(eslint.format())
});
`touch .eslintrc` instead of .eslint
these two steps may help you!
Run the command ember init.
When it asks for overwriting the existing file(s). Type n to skipping overwriting the file.
Now it will automatically create required files like .eslintrc, etc.
For me the same issue occurred when i copied my folder except dist, dist_production and node_modules folder to another system and tried running ember build.

Categories