Skip to content

Commit c60ee27

Browse files
authored
fix(runner): timeout long sync hook (#7289)
1 parent 33ab8a2 commit c60ee27

File tree

3 files changed

+30
-16
lines changed

3 files changed

+30
-16
lines changed

packages/runner/src/context.ts

+8-14
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ export function withTimeout<T extends (...args: any[]) => any>(
5454

5555
function resolve(result: unknown) {
5656
clearTimeout(timer)
57+
// if test/hook took too long in microtask, setTimeout won't be triggered,
58+
// but we still need to fail the test, see
59+
// https://github.com/vitest-dev/vitest/issues/2920
60+
if (now() - startTime >= timeout) {
61+
reject_(new Error(makeTimeoutMsg(isHook, timeout)))
62+
return
63+
}
5764
resolve_(result)
5865
}
5966

@@ -68,20 +75,7 @@ export function withTimeout<T extends (...args: any[]) => any>(
6875
// the result is a thenable, we don't wrap this in Promise.resolve
6976
// to avoid creating new promises
7077
if (typeof result === 'object' && result != null && typeof result.then === 'function') {
71-
result.then(
72-
(result) => {
73-
// if sync test/hook took too long, setTimeout won't be triggered,
74-
// but we still need to fail the test, see
75-
// https://github.com/vitest-dev/vitest/issues/2920
76-
if (now() - startTime >= timeout) {
77-
reject(new Error(makeTimeoutMsg(isHook, timeout)))
78-
}
79-
else {
80-
resolve(result)
81-
}
82-
},
83-
reject,
84-
)
78+
result.then(resolve, reject)
8579
}
8680
else {
8781
resolve(result)

test/cli/fixtures/fails/test-timeout.test.ts

+19-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { expect, suite, test } from 'vitest'
1+
import { beforeAll, beforeEach, expect, suite, test } from 'vitest'
22

33
test('hi', async () => {
44
await new Promise(resolve => setTimeout(resolve, 1000))
@@ -11,6 +11,24 @@ test('timeout on long synchronous task', async () => {
1111
}
1212
}, 15)
1313

14+
suite('timeout beforeAll', () => {
15+
beforeAll(() => {
16+
const start = Date.now();
17+
while (Date.now() < start + 20) {}
18+
}, 16)
19+
20+
test("ok", () => {})
21+
})
22+
23+
suite('timeout beforeEach', () => {
24+
beforeEach(() => {
25+
const start = Date.now();
26+
while (Date.now() < start + 20) {}
27+
}, 17)
28+
29+
test("ok", () => {})
30+
})
31+
1432
suite('suite timeout', {
1533
timeout: 100,
1634
}, () => {

test/cli/test/__snapshots__/fails.test.ts.snap

+3-1
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,10 @@ exports[`should fail test-timeout.test.ts 1`] = `
118118
"Error: Test timed out in 20ms.
119119
Error: Test timed out in 200ms.
120120
Error: Test timed out in 100ms.
121+
Error: Hook timed out in 17ms.
121122
Error: Test timed out in 15ms.
122-
Error: Test timed out in 10ms."
123+
Error: Test timed out in 10ms.
124+
Error: Hook timed out in 16ms."
123125
`;
124126
125127
exports[`should fail unhandled.test.ts 1`] = `

0 commit comments

Comments
 (0)