My Jest test has a timeout configured. My test performs potentially long-running work. I want the code to abort when Jest times out. How do I do that?
Here's the code:
describe('timeout', () => {
jest.setTimeout(1000);
test('timeout', async () => {
// Emulates long-running work
await new Promise((resolve) => setTimeout(resolve, 2000));
// Follow-up work after long-running work
expect(true).toBeTruthy();
console.log('waited 2s');
});
});
When Jest times out after 1s, I want everything after "Follow-up work after long-running work" to not be executed. How do I do that? Is there a way to ask Jest whether the timeout has been reached?
Current behavior of above code:
FAIL timeout.test.js
timeout
✕ timeout (1002 ms)
● timeout › timeout
thrown: "Exceeded timeout of 1000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
2 | jest.setTimeout(1000);
3 |
> 4 | test('timeout', async () => {
| ^
5 | // Emulates long-running work
6 | await new Promise((resolve) => setTimeout(resolve, 2000));
7 |
at timeout.test.js:4:5
at Object.<anonymous> (timeout.test.js:1:83)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.197 s, estimated 2 s
Ran all test suites matching timeout.test.js/i.
● Cannot log after tests are done. Did you forget to wait for something async in your test?
Attempted to log "waited 2s".
8 | // Follow-up work after long-running work
9 | expect(true).toBeTruthy();
> 10 | console.log('waited 2s');
| ^
11 | });
12 | });
13 |
at console.log (node_modules/@jest/console/build/CustomConsole.js:187:10)
at Object.<anonymous> (timeout.test.js:10:17)
Desired behavior:
FAIL timeout.test.js
timeout
✕ timeout (1002 ms)
● timeout › timeout
thrown: "Exceeded timeout of 1000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
2 | jest.setTimeout(1000);
3 |
> 4 | test('timeout', async () => {
| ^
5 | // Emulates long-running work
6 | await new Promise((resolve) => setTimeout(resolve, 2000));
7 |
at timeout.test.js:4:5
at Object.<anonymous> (timeout.test.js:1:83)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.197 s, estimated 2 s
Ran all test suites matching timeout.test.js/i.
(no warnings after this)