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.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
}
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" })
}