jest: JEST tests complete successfully but returns exit status 1

I run JEST tests using npm run test:jest and the corresponding entry in package.json is

"test:jest": "jest --config=./jest.config.js",

All tests run successfully, but returns with exit code 1

Test Suites: 1 skipped, 106 passed, 106 of 107 total
Tests:       10 skipped, 657 passed, 667 total
Snapshots:   14 files obsolete, 0 total
Time:        34.453s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @vc/toolchain@3.3.0 test:jest: `jest --config=./jest.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @vc/toolchain@3.3.0 test:jest script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/.npm/_logs/2019-12-18T13_01_11_869Z-debug.log

10 silly lifecycle @vc/toolchain@3.3.0~test:jest: Args: [ '-c', 'jest --config=./jest.config.js' ]
11 silly lifecycle @vc/toolchain@3.3.0~test:jest: Returned: code: 1  signal: null
12 info lifecycle @vc/toolchain@3.3.0~test:jest: Failed to exec test:jest script
13 verbose stack Error: @vc/toolchain@3.3.0 test:jest: `jest --config=./jest.config.js`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:915:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid @vc/toolchain@3.3.0
15 verbose cwd /workspace/vc.src/vco/src/server/node
16 verbose Linux 3.13.0-163-generic
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "test:jest"
18 verbose node v8.17.0
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 1
22 error @vc/toolchain@3.3.0 test:jest: `jest --config=./jest.config.js`
22 error Exit status 1
23 error Failed at the @vc/toolchain@3.3.0 test:jest script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

I am not sure why the process exits with status code 1 even though all tests pass.

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 79
  • Comments: 109

Commits related to this issue

Most upvoted comments

Repro please, or it didn’t happen

Snapshots: 3 obsolete, 26 passed, 26 total obsolete - are the cause of the error, after their removal, the error is gone.

Anyway, without a repro there’s nothing I can do. Please make sure you’re on the latest version and try to come up with a minimal case by filtering out some tests until you get a correct exit code.

@smith-xyz you should never run Jest with -u on CI. The generated snapshot may likely be wrong and your tests will still pass, giving you false sense of security.

I was facing a similar issue using when I was running:

jest --silent --runInBand --testPathPattern=index.spec\\.tsx$

Which cause my tests to run, but the process was exiting with exit code 1. However, changing this to:

jest --silent --maxWorkers=2 --testPathPattern=index.spec\\.tsx$

i fixed it changing --runInBand to --maxWorkers=2 but i dont know the reason why it was failing.

Solved: i needed to add await to fireEvent like await fireEvent.press(button);

Also, possibly there is a misleading await on my code which can cause this problem. 🤔

A lot of people have already pointed out but let me summarize a quick answer to a new visitor on this thread.

  • Tests fail on the CI due to a single worker process (in GitHub Actions in my case) which is not the case in our local machines. Try adding maxWorkers=2 to your test script and the tests will pass on the CI without changing the machine from ubuntu-latest to macos-latest.
  • To know the exact reason why the tests fail on the CI try adding --runInBand to your test script and you will see it locally returning an exit status code of 1 as well.

Getting the same here pretty frequently when running in CI. It is intermittent but frequent enough to have started slowing things down.

Test Suites: 2 skipped, 233 passed, 233 of 235 total
Tests:       25 skipped, 1009 passed, 1034 total
Snapshots:   1 passed, 1 total
Time:        721.58s
Ran all test suites.
error Command failed with exit code 1.
error Command failed with exit code 1.
error Command failed.
Exit code: 1

I had a similar issue in my GH actions where all tests would pass but still exit 1.

Test Suites: 10 passed, 10 total
Tests:       38 passed, 38 total
Snapshots:   0 total
Time:        98.33s
Ran all test suites.
npm ERR! Test failed.  See above for more details.
##[error]Process completed with exit code 1.

It was all fine on my local machine. The only thing I found that was different was the machine the test was running on in GH Actions. So I changed my GH action runs-on from ubuntu-latest to macos-latest and no more exit code 1 🎉

This was a face palm moment, I was digging around the tests and code trying to find some sign of why our CI test script was not running. Then it hit me. We are using snapshot tests and maybe the test suite could not run due to not being able to execute the snapshots. After adding -u to our npm run test:ci script, this resolved the issue.

I leave this here in case this saves someone some time in considering that maybe the script cannot execute the snapshots.

I’m seeing the same issue and now CI is failing all buddy builds.

I just spent a bunch of time debugging this. For me, this was caused by the Cannot log after tests are done. Did you forget to wait for something async in your test? error. Quite confusingly, this often didn’t reproduce locally, but only on CI.

My working theory is that the last test in one of our suites kicks off a promise to make a request, but then the test completes before that promise executes. We’re using MSW to mock requests, but MSW gets cleaned up because the suite is complete, so a real request is made to a real server rather than being intercepted.

Here is the issue that’s tracking this case. https://github.com/facebook/jest/issues/11132 IMO it’s a very bad user experience to have no tests fail, but exit with a non-0 code. If logging after cleanup is really so bad that it constitutes a failing exit code, we should at least be able to link it back to the test that causes the problem and retroactively fail it.

I’m running into same issue, test passess successfully but jest returns status code 1 and npm errors.

PASS  src/test/restart.test.ts
  √ restart (3438ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.298s, estimated 6s
npm ERR! code ELIFECYCLE
npm ERR! errno 1

Not sure if it’s related but I’m using TypeScript and doing a async test with child processes and this seems so far to be the only case where I’ve encountered such behaviour. Though there seems to be no difference whether I’m running with ts-jest transform or directly against built js files. Oh and everything is updated to latest versions.

In my case what happened was that I got Cannot log after tests are done. Did you forget to wait for something async in your test? errors, but that didn’t cause Jest to exit with code 1 anywhere, except my CI. I finally realized that my CI is probably running on a single CPU so I ran locally with --runInBand and eureka, jest fails locally as well. Now I gave the error some meaning and indeed it was the one causing Jest to fail. The bug here was that when running non in bad, it does not cause a filaure… I will open a new bug for that

We are experiencing this too. Locally the tests are passing and the process is returning 0 (MacOS) But on the GitLab CI (node:12.13.0) it is returning 1, even after all the tests passes with no diff in snapshots

Solution in my case:

  1. Find an error in the log: “Cannot log after tests are done. Did you forget to wait for something async in your test?”
  2. Find a test which produce the error and change “async await” logic to “Promise” and finish the test by calling “done()” command.

https://youtu.be/m-v_cXLGhEg https://habr.com/ru/post/710342/](https://habr.com/ru/post/710342/

In my case, it was due to not meeting the minimum coverage requirement.

Another case I’ve found is that jest will return an exit code of 1 if any logging happens after teardown.

…If we only knew, where to add async/await

For us, this issue presented after upgrading to Node.js 18 and adopting npm 8. A successful exit status code when run via npm was only found after disabling coverage reporting 😑

I then identified that the collectCoverageFrom pattern was the cause. Not sure what was wrong with it, or why it’d stop working after a Node.js upgrade though 🤷🏻‍♂️

collectCoverageFrom: ['<rootDir>/src/**/*.ts'],

Simply removing this configuration resolved the issue. Coverage just includes some unnecessary files now. I couldn’t figure out how to make it happy with a pattern specified.

Got it. I had a couple of these:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

which are probably down to bad mocks but I was just ignoring in previous versions of Jest.

I narrowed down all my tests to a specific file and despite only 10 or so tests passing that log would appear and the tests would still exit with error.

So I guess the tests should be failing because of this bad error, but maybe a specific jest error would be better than just exit 1!

p.s. it was actually due to an old function using Promise.resolve().then() that was leaking out. The test was bad. I refactored to async/await and made sure the test was also async

i fixed it changing --runInBand to --maxWorkers=2 but i dont know the reason why it was failing.

Solved: i needed to add await to fireEvent like await fireEvent.press(button);

So I changed my GH action runs-on from ubuntu-latest to macos-latest and no more exit code 1

Same experience on an Azure Pipeline build.

If you are using Node.js 20.x, ensure nothing in your tested code is setting the process.exitCode property to non-zero.

This makes any version of Jest fail, even when all tests are passing. This is being tracked here: https://github.com/jestjs/jest/issues/14501

I had the same issue. After debugging jest, i found a line in TestScheduler.js:

  aggregatedResults.success = !(
    anyTestFailures ||
    aggregatedResults.snapshot.failure ||
    anyReporterErrors
  );

Where aggregatedResults.snapshot.failure was true.

Deleting and recreating snapshots solved my problem , because one of my snap files contained and unused entry.

Same issue here, any solutions?

Test Suites: 1 passed, 1 total
--
24-Mar-2020 18:09:46 | Tests:       4 passed, 4 total
24-Mar-2020 18:09:46 | Snapshots:   1 obsolete, 1 passed, 1 total
24-Mar-2020 18:09:46 | Time:        4.2s
24-Mar-2020 18:09:46 | Ran all test suites.
24-Mar-2020 18:09:46 | npm ERR! code ELIFECYCLE
24-Mar-2020 18:09:46 | npm ERR! errno 1
24-Mar-2020 18:09:46 | npm ERR! @app/front@ test:ci: `jest --ci`
24-Mar-2020 18:09:46 | npm ERR! Exit status 1

Edit: Upgrading node to latest version solved the issue for me

I’ve encountered the same variation as @shousper above https://github.com/jestjs/jest/issues/9324#issuecomment-1319514254

We have two options to fix it:

  • remove collectCoverageFrom as suggested by @shousper
  • add coverageProvider: 'v8' - if you cannot afford to remove collectCoverageFrom

I have this same issue after upgrading from jest 27.5.1 to 28.1.1 node 18.12.1

If someone from jest team would like to take a deeper look, I can contribute and go deeper.

I’m glad this error doesn’t bother you any more, @brunolnetto .

I met the same error, and then the command jest --detectOpenHandles told me more details about failed reasom

# package.json
{ 
 scripts: {
  "test": "jest --detectOpenHandles "
}
}

https://jestjs.io/zh-Hans/docs/cli#--detectopenhandles

well fixed this by changing runs-on to macos-latest and switching back to ubuntu-latest after one successful run

Be aware that the mac os image spends 10x more credits. Later I did revert to Ubuntu and it worked again. Still do not know what was causing this issue.

I bumped into a similar issue today, and I had such a dumb setup mistake that I wanted to share how I fixed it.

Screen Shot 2021-12-15 at 12 37 31

My project didn’t hit the coverage benchmarks, and it broke the pipeline even without failing tests.

My tests are failing on CircleCI, same error… even though all tests are passing, I’m getting the same. Even trying to remove the coverageThreshold, it still fails 🤔

I solved moving to Github Action and using macos-latest as described here: https://github.com/facebook/jest/issues/9324#issuecomment-643783847

But it’s not feasible… running Github Actions with a macOS runner costs 10x than using the Linux runner. It’s awesome there’s a fix for this issue, but worth calling out the cost difference - you’ll eat up your Github minutes much, much faster.

EDIT (Update):

Solved after bumping Node version on CircleCI to circleci/node:14-browsers

I ran into this issue in two different ways while using ts-jest. I fixed both:

1.) I left a fit( in my test suite. This for whatever reason was claiming that I had a pending test (rather than skipped). This caused npm to exit with an error code as 1. Solution: Removed the f that I accidentally left. This file was now fine and npm was exiting with exit code of 0.

2.) I was using a nyan cat jest reporter (because why not?), while also having type-specific errors. Solution: I removed the nyan cat jest reporter and used the default reporter. This made the TypeScript related type errors show up. I specifically changed a tsconfig.json value (noImplicitAny: true) recently and had some errors but the nyan cat jest reporter was silencing these errors.

In my case, it was just related to code coverage falling under the defined thresholds in jest config. In our case, I just lowered those thresholds to the actual values and everything worked fine.

My fix was by adding: "coverageReporters": [ "text-summary", "lcov" ] to my jest configuration

I’m not deep enough in the code. The error doesn’t reproduce on my local Mac, only on Semaphore CI testing.

Getting exist status 1 on semaphore CI, OS ubuntu2004 every time on the first execution of the test.

All PASS, but the process finishes with error 1. The tests run with coverage, otherwise all ok.

The second run is ok. MacOS local tests are ok.

runInBand/maxWorkers don’t help.

Adding async await inside the test solved this issue for me

@DamianArado maxWorkers=2 does the trick, thanks!

Experienced similar issue with Jest 27.1.0 on GitLab CI.

npx jest --ci --coverage --runInBand --colors

Fixed with adding --silent flag.

npx jest --ci --coverage --runInBand --colors --silent

Hi everyone

Did you use forEach + async/await in your tests?

I have resolved this issue, use for await...of instead forEach

CleanShot 2021-11-01 at 22 28 00@2x

ref: https://stackoverflow.com/a/54751807/5847276

I was facing the same situation which - in my case - I could also pin down to this error:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

Following the solution of this StackOverflow thread I was able to make the error disappear and as a result the exit code is now 0 - both locally as in CI/CD by simply changing testEnvironment: 'node' to testEnvironment: 'jsdom'.

Note using ``testEnvironment: ‘jsdom’` comes with some other potential caveats so it might not be a workable solution for everyone. I feel there’s still an underlying problem in Jest that needs be resolved.

maybe some error interrupt the test case, for example

expect(current.value).toEqual(true)

if the current is undefined, will cause this problem

to solve this problem, to make sure current is valid or use try...catch...to wrap the expect statement

I too ran into the same issue. But for me, it started working just after I removed the obsolete snapshot test. I removed the obsolete snapshot by running --updateSnapshot once in my local machine and then pushing the updated snapshot. PS: I am on ubuntu-latest

my tests seem to fail if I have image snapshots (jest-screenshot) created on macos they fail inside docker. If I remove the snapshots and run the tests inside docker, no matter how many times I run the tests they will pass.

Had this issue after upgrading RN to 0.63.3 from 0.61, it was actually caused by an outdated enzyme-adapter-react-16 It would seem that jest masks issues. that occur outside of individual tests.

https://github.com/facebook/jest/issues/6434#issuecomment-647589824

I am using react-native-testing-library and what resolved this error for me was to simply make the callback of the test case async like

it('your test case', () => {...})

becomes:

it('your test case', async () => {...})

This worked for me

So I changed my GH action runs-on from ubuntu-latest to macos-latest and no more exit code 1 🎉

After 3 hours of messing around I ended up using this.

Anyway, without a repro there’s nothing I can do

Happy to. Any criteria/preferred structure? I can make a repo with a repro if that suits you.

I had the same problem, what worked for me was moving to an older build.

I used jest@20.0.4 rather than current version

yarn add jest@20.0.4

Let me know if this works!

Hi @thymikee

This happens in our repo and I am not able to create a reproducible sample repo. But what I could say is that the following command runs successfully,

node /workspace/vc/vco/src/server/node/node_modules/.bin/jest --config=./jest.config.js

<Runs all the tests successfully >

Test Suites: 1 skipped, 106 passed, 106 of 107 total
Tests:       10 skipped, 657 passed, 667 total
Snapshots:   15 files obsolete, 0 total
Time:        24.668s, estimated 33s
Ran all test suites.

whereas when running JEST cases via npm is failing.

$ npm run test:jest

<Runs all the tests successfully >


Test Suites: 1 skipped, 106 passed, 106 of 107 total
Tests:       10 skipped, 657 passed, 667 total
Snapshots:   19 files obsolete, 0 total
Time:        25.982s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @velocloud/toolchain@3.3.0 test:jest: `jest --config=./jest.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @velocloud/toolchain@3.3.0 test:jest script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vagrant/.npm/_logs/2019-12-18T15_15_30_620Z-debug.log

jest.config.js

'use strict';

module.exports = {
    "projects": [
        {
            name: "vc-core",
            displayName: "Jest - VC services",
            bail: false,
            clearMocks: false,
            collectCoverage: false,
            collectCoverageFrom: [
                '**/lib/sample/getSample.js'
                
            ],
            coverageDirectory: "/test-output/coverage",
            coverageReporters: [
                "json",
                "text-summary",
                "cobertura"
            ],
            reporters: [
                "default",
                "./common/VcTestReporter",
                "jest-junit"
            ],
            setupFilesAfterEnv: ["./common/setup.js"],
            testEnvironment: "./common/VcTestEnv.js",
            testMatch: [
                "**/__tests__/**/*.js"
            ],
            testPathIgnorePatterns: [
                "__tests__/aws.js",
               
            ],
            verbose: true,
        }
    ]
};