Skip to content

Commit

Permalink
fix(runner): timeout long sync hook (#7289)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa authored Jan 21, 2025
1 parent 33ab8a2 commit c60ee27
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 16 deletions.
22 changes: 8 additions & 14 deletions packages/runner/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ export function withTimeout<T extends (...args: any[]) => any>(

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

Expand All @@ -68,20 +75,7 @@ export function withTimeout<T extends (...args: any[]) => any>(
// the result is a thenable, we don't wrap this in Promise.resolve
// to avoid creating new promises
if (typeof result === 'object' && result != null && typeof result.then === 'function') {
result.then(
(result) => {
// if sync test/hook took too long, setTimeout won't be triggered,
// but we still need to fail the test, see
// https://github.com/vitest-dev/vitest/issues/2920
if (now() - startTime >= timeout) {
reject(new Error(makeTimeoutMsg(isHook, timeout)))
}
else {
resolve(result)
}
},
reject,
)
result.then(resolve, reject)
}
else {
resolve(result)
Expand Down
20 changes: 19 additions & 1 deletion test/cli/fixtures/fails/test-timeout.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expect, suite, test } from 'vitest'
import { beforeAll, beforeEach, expect, suite, test } from 'vitest'

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

suite('timeout beforeAll', () => {
beforeAll(() => {
const start = Date.now();
while (Date.now() < start + 20) {}
}, 16)

test("ok", () => {})
})

suite('timeout beforeEach', () => {
beforeEach(() => {
const start = Date.now();
while (Date.now() < start + 20) {}
}, 17)

test("ok", () => {})
})

suite('suite timeout', {
timeout: 100,
}, () => {
Expand Down
4 changes: 3 additions & 1 deletion test/cli/test/__snapshots__/fails.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,10 @@ exports[`should fail test-timeout.test.ts 1`] = `
"Error: Test timed out in 20ms.
Error: Test timed out in 200ms.
Error: Test timed out in 100ms.
Error: Hook timed out in 17ms.
Error: Test timed out in 15ms.
Error: Test timed out in 10ms."
Error: Test timed out in 10ms.
Error: Hook timed out in 16ms."
`;
exports[`should fail unhandled.test.ts 1`] = `
Expand Down

0 comments on commit c60ee27

Please sign in to comment.