How to prevent Jest from printing all skipped tests? - jestjs

I'm trying to run just one Jest test, and am I using the following command:
jest --config=jest.config.js --runInBand --bail --forceExit "services_rest_Api" "-t" "should list all tag notes"
With the following config:
module.exports = {
testMatch: [
'**/tests/**/*.js',
],
testPathIgnorePatterns: [
'/node_modules/',
'tests/support/',
'test-utils.js',
'file_api_driver.js',
],
testEnvironment: 'node',
setupFilesAfterEnv: ['./jest.setup.js'],
};
Whenever I run this, it displays the filtered test on top, but also all the skipped one below:
PASS tests/services_rest_Api.js
services_rest_Api
✓ should list all tag notes (852 ms)
○ skipped should ping
○ skipped should handle Not Found errors
○ skipped should get folders
// ... And many more of these
Which means I need to scroll up by a lot to actually see the results for the test I was running. So I'm wondering, is there any way to prevent Jest from printing all these skipped tests? I didn't include the verbose anywhere so I thought it shouldn't print this but it still does. Any idea?

To disable verbosity you could either set it:
cli
jest --verbose=false
or in:
jest.config.json/package.json
{
"verbose": false
}
and even the documentations says by default it's false by default
it's enabled when you run tests for a single file

Related

Jest fails with 'Cannot find module' when restricted to a single suite but succeeds when testing multiple suites

I have a typescript project containing multiple Jest test suites. If I run all of the suites together using
npm test
then all the tests are executed.
I can filter the tests that run by using a command like
npm test -- LayoutView
Jest then only executes the tests from modules whose names contain the text LayoutView. We get a response
> jest --config=./configs/jest.config.ts "LayoutView"
PASS tests/actions/LayoutViewHide.test.ts
PASS tests/actions/LayoutViewCopy.test.ts
PASS tests/actions/LayoutViewMove.test.ts
Test Suites: 3 passed, 3 total
Tests: 47 passed, 47 total
Snapshots: 0 total
Time: 6.724 s
Ran all test suites matching /LayoutView/i
However if I further restrict the pattern so that it only matches a single test file like this then it fails.
npm test -- LayoutViewH
giving an error like this:
> jest --config=./configs/jest.config.ts "LayoutViewH"
FAIL tests/actions/LayoutViewHide.test.ts
● Test suite failed to run
Cannot find module 'source-map-support' from 'node_modules/#cspotcode/source-map-support/source-map-support.js'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:306:11)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.095 s, estimated 5 s
Ran all test suites matching /LayoutViewH/i.
It seems that whenever I try to test from a single suite it fails, whenever the test covers multiple files then it succeeds. This is preventing me from debugging a failed test, since VSCode is trying to run a single test, and fails with the same error message I can see in the command line.
Looking at Jest - Cannot find module 'source-map' from 'source-map-support.js' I checked the moduleDirectories property in my jest.config.ts file. It reads
moduleDirectories: ['node_modules', 'src'],
I need to have 'src' here since I am using absolute paths within my code, relative to a directory called src below my root directory.
Besides if I have the includes miss-configured, why does it work when testing several suites at once? Any idea what might be causing this?
I am running:
node --version: v16.15.1
Jest version: 26.6.3
My jest.configure.ts file reads
module.exports = {
rootDir: '../',
roots: [ '<rootDir>/tests/' ],
transform: {
'.+\\.(css|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.tsx?$': 'ts-jest',
'^.+\\.js$': '<rootDir>/node_modules/babel-jest'
},
testRegex: '\\.test\\.(ts|tsx|js)$',
moduleFileExtensions: ['ts', 'tsx', 'js'],
moduleDirectories: ['node_modules', 'src'],
testEnvironment: 'node',
};
The relevant part of the "package.json" file contains
{
"scripts": {
"test": "jest --config=./configs/jest.config.ts"
}
}

Difference in running one and many files in jest

I'm using jest (^28.1.3) for running unit and e2e tests on backend (Apollo Server, TypeORM and PostgreSQL). There aren't problems to run unit tests (one file, two or all), but I have a problem with e2e testing.
On local machine
If I run one file with e2e tests (e.g. regression.e2e-spec.ts), I'll get an error.
If I run two files (e.g. regression.e2e-spec.ts + someUnit.test.ts, or regression.e2e-spec.ts + otherE2ETest.e2e-spec.ts), I won't get any error, testing will finished successful.
On GitHub Actions
I get same error in any cases (run one, two or all files)
May jest execute tests in main process/thread when it finds only one file? And split execution on several process when find several files?
The problem might be in an isolation, with one file environment isn't clean.
Files are filtered in jest.config.js, write file name in testMatch.
/** #type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
roots: ['<rootDir>/src'],
testEnvironment: 'node',
testMatch: ['**/src/**/*.(test|e2e-spec).ts'], // keep in sync with src/__test__/setup/E2ERegExp.ts
globalSetup: './src/__test__/setup/globalSetup.ts',
globalTeardown: './src/__test__/setup/globalTeardown.js',
setupFilesAfterEnv: ['./src/__test__/setup/setup.ts'],
transform: {
'^.+\\.ts': 'ts-jest',
},
};
In globalSetup and globalTeardown I setup and drop databases. In setup.ts run server and connect to db.
Tests are executed in parallel.
"docker:test": "RUN_DB=true NODE_OPTIONS=--max-old-space-size=4096 jest --colors --maxWorkers=50%",

Jest is failed to running with Mock files with Error Message Your test suite must contain at least one test

I have webpack and jest,I have my jest option setting as below:
"moduleNameMapper": {
"^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__tests__/__mocks__/fileMock.js",
"^.+\\.(css|less)$": "<rootDir>/__tests__/__mocks__/styleMock.js"
}
}
styleMock.js content:
export default '';
fileMock.js content:
export default 'test-file-stub';
Jest Fail to Run. with below error:
FAIL __tests__/__mocks__/fileMock.js
● Test suite failed to run
Your test suite must contain at least one test.
FAIL __tests__/__mocks__/styleMock.js
● Test suite failed to run
Your test suite must contain at least one test.
It's just that Jest should not try to execute those files as tests. You should change the testMatch in jest.config.js to only check for .spec.js files or .test.js files :
testMatch: [
"**/__tests__/**/*.[tj]s?(x)",
"**/?(*.)+(spec|test).[tj]s?(x)"
],

Console.log statements output nothing at all in Jest

console.log statements output nothing at all in Jest. This was working for me yesterday, and all of sudden, it's not working today. I have made zero changes to my config and haven't installed any updates.
I'm not using the --forceExit option. Still seeing this issue.
Jest suppresses the console log message by default. In order to show the console log message, set silent option to false at the command line
set --silent=false in the command line:
npm run test -- --silent=false
You can run both options together like this --watch --verbose false if you want to also be watching the files and see the output.
for one time runs just do --verbose false
As per comment on https://github.com/facebook/jest/issues/2441,
Try setting verbose: false (or removing it) in the jest options in package.json.
This is a pretty old question and still there's no accepted answer. However, none of the suggested solutions worked for me (settings like --silent --verbose etc.). The main problem is that Jest changes the global console object. So, the easiest solution is to not use the global console object.
Instead import dedicated log functions from the console module and work with those:
import { error } from "console";
error("This is an error");
As easy as that.
Try using console.debug() instead.
Run console.debug('Message here', yourValueHere) inside test function and it should show in the console output when running test script. You can verify if it works using Ctrl+F and find Message here in the standard output.
This does the trick of showing output in the console, while it is not an answer quite on how to use console.log I understand.
I am running #testing-library/jest-dom and jest-junit 12.0.0 as devDependencies.
jest-junit has a minimal configuration of
"jest-junit": {
"usePathForSuiteName": "true"
},
in package.json. This is mainly to configure coverage reporting.
jest is configured like this:
"jest": {
"testMatch": [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[jt]s?(x)",
"!**/utilities.ts",
],
Check for your command line flags in package.json to see that you don't have --silent in there.
in addition to --verbose option which can cause this as mentioned, be aware that the --watch may also cause this bug.
One of the potential reason that logging is not printing is due to console.log has been mocked. Something as below
// jest-setup.js
global.console = {
// eslint-disable-next-line no-undef
log: jest.fn(), // console.log are ignored in tests
// log: console.log,
// Keep native behaviour for other methods, use those to print out things in your own tests, not `console.log`
error: console.error,
warn: console.warn,
info: console.info,
debug: console.debug,
};
// package.json
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"setupFilesAfterEnv": [
"#testing-library/jest-native/extend-expect",
"<rootDir>/src/config/jest-setup.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.test.{ts,tsx}"
]
},
This is commonly used if you wish to disable console.log in jest
Also be sure that your jest config does not have silent: true. In my case, I didn't realize that someone else had added that to our config.
I don't see it in the list of config options, but the command line flag is documented here.
If using Webstorm with Jest configuration, click on the file name instead of the test name.
Having tried a few of the config options in the previous replies, using console.debug() instead of console.log() worked.
In my case, the issue was caused by [only] flag in:
it.only() or test.only('some text',()=>{})
According to the v27 docs silent is what you want here. verbose false (the default) prevents Jest from outputting the result of every test in a hierarchy while silent true (the default) will:
Prevent tests from printing messages through the console.
Use npx jest --silent false if you want to run Jest with that option from the CLI. Tested this just now with console.log and it works as expected.
Tried the advice given regarding jest config settings to no avail. Instead, in my case, the issue seemed related to not awaiting asynchronous code:
test("test", async () => {
console.log("Does output")
new Promise(resolve => {
// some expectation depending on async code
setTimeout(() => resolve(console.log("Does not output")) , 1)
})
})
Rather, awaiting the promise does output the async log:
test("test", async () => {
console.log("Does output")
await new Promise(resolve => {
// some expectation depending on async code
setTimeout(() => resolve(console.log("Does output")) , 1)
})
})
Possibly related background:
https://github.com/facebook/jest/issues/2441
Try using console.info() which is an alias for console.log(). I tried almost all the above answers but still console.log() didn't worked for me by any means. So, used console.info() which did the work.
This is what worked for me: jest --verbose true
In my case the problem was that the logs where made when the module is required, so before the start of an actual test case. Change from a top-level import to using require inside the test case fixed the problem.
In my case the problem was importing the functions from the compiled version (present in dist folder) instead of the src folder. And therefore it was using the old version. So rebuilding the project and/or importing from src fixed my issue.
On MacOS with jest version 26.6.3 I had to append --silent="false"
renaming my file to index.test.js from index.spec.js did the trick for me.

Is there a good report for jest test case?

I am using jest to test my reactjs application. It works fine but jest doesn't give me a good report about test case results. The output of jest shows each test suite followed by its output. I have more than 50 test suites and it is hard for me to scroll up to check each failed test cases. Is there a brief jest report which printing a brief summary about the whole test cases?
below is my jest.conf file:
{
"testRegex": "/tests/.*\\.test\\.jsx?$",
"testEnvironment": "node",
"roots": ["./src"],
"coverageReporters": ["text-summary", "html"]
}
There is also a JEST HTML Reporter module which you might find useful.
It's configurable to specify what level of detail you want to show in the test report for failures
https://www.npmjs.com/package/jest-html-reporter
You can run jest with the --coverage flag.
If you want something different than the default reporters, you have to set them in your jest config file.
jest.json
{
"coverageReporters": ["text-summary", "html"]
}
text-summary gives you a short summary beneath all tests that tells you how many suites/tests are successful/failed.
html gives you a some html pages that you can browse through to see exactly what got tested.
CLI
$ ./node_modules/.bin/jest --config ./path/to/jest.json --coverage
You might want to adjust which files are covered etc.
See all coverage options in the jest docs.
https://github.com/jest-community/awesome-jest#reporters contains a list of other reporters. jest-stare will let you filter off passing tests so you can just see the ones that failed.
Use Istanbul to generate Reports
In the Script section of the Package.json just add :
"scripts": {
"test": "jest",
"test-coverage": "jest --coverage",
}
Save the project and run below command:
Yarn test : For Terminal Coverage
Yarn test-coverage for Report Generation.Find HTML report in Coverage > Icov-report >index.html
If you can use a web-based reporter try Tesults - a reporter for Jest is available to help with integration: https://www.npmjs.com/package/jest-tesults-reporter.
You main issue, with respect to navigating test suites is handled well. I should add a disclaimer that I work at Tesults, but on the other hand if this is for a very small team or it's open source it is free to use, just contact support.

Resources