'Jest exits before tests are finished running
I'm trying to create Jest unit tests for async functions. The docs (https://jestjs.io/docs/asynchronous) are quite straightforward and have been used to write the following function and unit test:
// Code
async function fetchData() {
await new Promise(resolve => setTimeout(resolve, 1000));
return 1
}
// Test
test('test should fail', async function() {
const data = await fetchData()
expect(data).toBe('abc')
});
It seems like Jest exits before the async function gets a chance to finish as you can see from the result below.
$ npm test
> test
> jest
RUNS ...mymodule/__tests__/mymodule.test.js
As many have suggested in other posts, I've tried to set a timeout value - both globally and locally to the test. But this hasn't helped. Maybe this has something to do with my environment, but I haven't found what could be the cause. Any suggestions?
- jest v27.5.1
- jest-dev-server v6.0.3 ( - have tried to remove this just in case, but did not help.)
- node v17.6.0
- npm v8.5.1
// jest.config.js
module.exports = {
testEnvironment: "node",
globalSetup: "./jest-setup", // tested with and without
globalTeardown: "./jest-teardown", // tested with and without
testTimeout: 30000, // tested with and without
}
Solution 1:[1]
I removed globalSetup from the config, and that fixed the issue. I thought I'd tried that before, but apparently not.
The cause was a command within the initialisation of jest-dev-server in globalSetup that failed. Because of that, Jest quit without letting me know that it had failed. Example is shown below:
const { setup } = require("jest-dev-server")
module.exports = async () => {
await setup({ command: "theFailing cmd" })
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel |
