Unfortunately setting jest.setTimeout(10000)
in a describe block will apply to tests outside the scope of that describe block.
One solution is to set a beforeEach
and afterEach
in the describe block that sets the timeout to the increased value before each test, and then updates it back to the default value (5000, or whatever you have configured) after each test finishes.
Example showing that setTimeout affects tests outside the describe:
describe('Timeout Shenanigans', () => {
describe('Custom Timeout 10000', () => {
jest.setTimeout(10000)
it('Should Pass, Under Custom Timeout', async () => {
await delay(7500);
})
it('Should Fail, Over Custom Timeout', async () => {
await delay(11000);
})
});
describe('Default Timeout 5000', () => {
it('Should Fail, Over Default Timeout', async () => {
await delay(5500);
})
it('Should Pass, Under Default Timeout', async () => {
await delay(4900);
})
it('Should Pass, Specifies Own 12000 Timeout', async () => {
await delay(11000);
}, 12000)
});
});
=>
Timeout Shenanigans
Custom Timeout 10000
✓ Should Pass, Under Custom Timeout (7502 ms)
✕ Should Fail, Over Custom Timeout (10005 ms)
Default Timeout 5000
✓ Should Fail, Over Default Timeout (5504 ms)
✓ Should Pass, Under Default Timeout (4904 ms)
✓ Should Pass, Specifies Own 12000 Timeout (11005 ms)
Notice the first 5000 case passes when it should have failed for exceeding the timeout, even though jest.setTimeout
is called in the other describe block. This can't be solved by re-ordering the describe blocks.
Example showing the beforeEach / afterEach solution:
describe('Timeout Shenanigans', () => {
describe('Default Timeout 5000', () => {
it('Should Fail, Over Default Timeout', async () => {
await delay(5500);
})
it('Should Pass, Under Default Timeout', async () => {
await delay(4900);
})
it('Should Pass, Specifies Own 12000 Timeout', async () => {
await delay(11000);
}, 12000)
});
describe('Custom Timeout 10000', () => {
beforeEach(() => {
jest.setTimeout(10000);
});
afterEach(() => {
jest.setTimeout(5000);
})
it('Should Pass, Under Custom Timeout', async () => {
await delay(7500);
})
it('Should Fail, Over Custom Timeout', async () => {
await delay(11000);
})
});
});
=>
Timeout Shenanagins
Default Timeout 5000
✕ Should Fail, Over Default Timeout (5003 ms)
✓ Should Pass, Under Default Timeout (4903 ms)
✓ Should Pass, Specifies Own 12000 Timeout (11005 ms)
Custom Timeout 10000
✓ Should Pass, Under Custom Timeout (7506 ms)
✕ Should Fail, Over Custom Timeout (10001 ms)