Introduction
Oftentimes while using jest
, some testcases bail with: Exceeded timeout of 5000 ms for a test
. An approach is to increase the timeout of the testcase or at test level or at config level(for all tests).
1. Set test timeout at testcase level
To increase test timeout at the testcase level, pass the timeout value in miliseconds to it
as the last argument, exhibit:
test(name, fn, timeout)
, test
(aliased as it
) is a global meaning there’s no need to implicitly import from jest
package.
More on Jest Globals here
// inside the test file
describe('Base API tests', () => {
const bridgeAPI = new BridgeApi({})
beforeAll(() => {
// some teardown and setup
})
it('fetches current server Health', async() => {
const health = await bridgeAPI.getServerHealth()
expect(health).toBe("ok")
})
}, 8000) // we pass a timeout value of 8000 ms to this test case
2. Setting timeout at Test level
Test timeout at test level(for all testcases in a given file). This can be done by calling jest.setTimeout
on the jest object at the top of the test file.
// inside the test file
const TIME_IN_SECONDS = 8 * 1000
jest.setTimeout(TIME_IN_SECONDS)
describe('Base API tests', () => {
const bridgeAPI = new BridgeApi({})
beforeAll(() => {
// some teardown and setup
})
it('fetches current server Health', async() => {
const health = await bridgeAPI.getServerHealth()
expect(health).toBe("ok")
})
}) // we pass a timeout value of 8000 ms to this test case
Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. This only affects the test file from which this function is called. The default timeout interval is 5 seconds if this method is not called. The jest object
3. Setting timeout at config level- affects all the tests
This can be set in testTimeout
property of test config object in jest.config.js
on jest@29.7
onwards.
import type {Config} from 'jest';
const config: Config = {
testTimeout: 8 * 1000 // 8seconds
};
export default config;
All tests will timeout after 8seconds including teardown hooks(afterAll
etc)
Read more about testTimeout
Find me on Twitter/ where I tweet about interesting topics on software development.