Repository navigation
Description
Clear and concise description of the problem
The text of the issue was generated by Claude Code and verified by me.
Vitest has multiple timeout configurations that interact in non-obvious ways, making it hard for users to understand which timeout controls which behavior:
| Config | Default (Node / Browser) | Governs |
|---|---|---|
testTimeout |
5s / 15s | Entire test body |
hookTimeout |
10s / 30s | Lifecycle hooks |
teardownTimeout |
10s | Process shutdown |
expect.poll.timeout |
1s | expect.poll() retries |
browser.providerOptions.actionTimeout |
0 (Playwright only) | Playwright page actions |
On top of these, vi.waitFor() and vi.waitUntil() have a hardcoded 1s default that is not configurable globally.
The core confusion:
expect.element().toBeVisible()usesexpect.poll.timeout, but users don't know this becauseexpect.elementfeels like a browser action, not a poll.page.getByRole('button').click()usesactionTimeout, but only in Playwright — it's buried underbrowser.providerOptions.actionTimeout, making it provider-specific for what should be a framework-level concept.- Hidden dynamic adjustment: In browser mode, both
expect.elementand locator actions secretly compute their timeout fromtestTimeout - elapsedTime - 100ms(seeprocessTimeoutOptionsinpackages/browser/src/client/tester/tester-utils.ts). This fires the action timeout beforetestTimeoutto produce better stack traces. Users are unaware this happens. - Timeouts are scattered across the config:
testTimeoutis top-level,expect.poll.timeoutis nested underexpect,actionTimeoutis underbrowser.providerOptions— there's no single place to see and reason about all timeouts. vi.waitFor/vi.waitUntildefaults are not configurable, so there's no way to align them with other timeouts without passing{ timeout }on every call.
Existing bug: concurrent tests break dynamic timeout adjustment
The dynamic timeout adjustment stores _currentTaskStartTime and _currentTaskTimeout directly on the singleton runner object (packages/runner/src/context.ts, lines 55–56). When concurrent tests run, each test overwrites these values when it starts, meaning:
- Test A starts at t=0 with timeout=15s → sets
_currentTaskStartTime=0,_currentTaskTimeout=15000 - Test B starts at t=1s with timeout=5s → overwrites to
_currentTaskStartTime=1000,_currentTaskTimeout=5000 - Test A's
expect.element()now computes remaining time from Test B's values → wrong timeout
Fix for Node.js: Use AsyncLocalStorage to scope _currentTaskStartTime and _currentTaskTimeout per-test. The runner already has access to Node APIs, and AsyncLocalStorage correctly propagates through await chains in concurrent tests.
Fix for Browser: In the browser, AsyncLocalStorage is not available. However, concurrent tests with async browser actions (locator interactions, expect.element) are already discouraged due to inherent flakiness — multiple tests driving the same page simultaneously leads to unpredictable results regardless of timeouts. The current singleton approach is acceptable here since browser tests run sequentially in practice. We should document this limitation explicitly and, if a concurrent browser test is detected, either:
- Skip the dynamic adjustment and fall back to the configured fixed timeout, or
- Warn that dynamic timeout adjustment is unreliable with concurrent browser tests
Suggested solution
Group all timeouts under a timeout namespace, and introduce 'auto' as a value that means "derive from remaining test time."
New config shape
export default defineConfig({
test: {
timeout: {
test: 15_000, // was: testTimeout (default: 5s node / 15s browser)
hook: 30_000, // was: hookTimeout (default: 10s node / 30s browser)
teardown: 10_000, // was: teardownTimeout (default: 10s)
action: 'auto', // NEW — browser actions, expect.element, locator ops
// or browser: 'auto'
// replaces: browser.providerOptions.actionTimeout
// 'auto' = remaining test time minus buffer
// number = fixed timeout in ms
poll: 1_000, // was: expect.poll.timeout (default: 1s)
// / 1000ms (node, since there's no test budget concept)
wait: 1_000, // NEW — default for vi.waitFor() / vi.waitUntil()
// / 1000ms (node)
},
},
})How 'auto' works
'auto' means: "derive the timeout from the remaining test budget at the moment the operation starts."
effective_timeout = min(
startTime + timeout.test - now() - buffer,
<per-call override if provided>
)
The buffer (currently 100ms) ensures the action-level timeout fires before testTimeout, producing a meaningful error with a good stack trace instead of a generic "test timed out" message.
In Node context (no browser), 'auto' falls back to sensible fixed defaults (1s for poll/waitFor) since the "remaining test budget" concept is less useful without async browser operations.
Inheritance & override rules
timeout.test (15s)
│
├── timeout.action: 'auto' | number
│ └── Used by: locator.click(), locator.fill(), expect.element(), screenshots
│
├── timeout.poll: 'auto' | number
│ └── Used by: expect.poll()
│
├── timeout.wait: 'auto' | number
│ └── Used by: vi.waitFor(), vi.waitUntil()
│
└── buffer (300-500ms) ensures children fire before parent
Per-call overrides always win:
// Uses timeout.poll (auto-derived from remaining test time)
await expect.poll(() => count).toBe(5)
// Explicit override — ignores timeout.poll, uses 3000ms
await expect.poll(() => count, { timeout: 3000 }).toBe(5)Backwards compatibility
The old flat names become aliases:
// These are equivalent:
{ testTimeout: 5000 }
{ timeout: { test: 5000 } }
// These are equivalent:
{ hookTimeout: 10000 }
{ timeout: { hook: 10000 } }
// These are equivalent:
{ expect: { poll: { timeout: 1000 } } }
{ timeout: { poll: 1000 } }If both old and new are specified, the new timeout.* takes precedence and a deprecation warning is emitted.
browser.providerOptions.actionTimeout continues to work as a provider-level override but is no longer the primary way to configure action timeouts.
What changes for users
Before (current — confusing):
export default defineConfig({
test: {
testTimeout: 15_000,
hookTimeout: 30_000,
expect: {
poll: {
timeout: 5_000, // also affects expect.element... somehow
},
},
browser: {
provider: playwright({
actionTimeout: 5_000, // Playwright-only, overrides dynamic calc
}),
},
},
})After (proposed — clear):
export default defineConfig({
test: {
timeout: {
test: 15_000,
hook: 30_000,
action: 'auto', // or 5_000 for a fixed value
poll: 'auto', // derives from remaining test time
},
},
})Today, setting timeouts dynamically requires the verbose vi.setConfig({ testTimeout: 100 }). With the new timeout namespace this would get worse: vi.setConfig({ timeout: { action: 2000 } }).
Introduce vi.setTimeout() as a focused shorthand:
// Number = set test timeout (most common case)
vi.setTimeout(5_000)
// Object = set specific timeouts for the current test/suite
vi.setTimeout({ test: 5_000, action: 2_000, poll: 1_000 })Signatures:
interface VitestUtils {
setTimeout(ms: number): void
setTimeout(options: {
test?: number
hook?: number
action?: number | 'auto'
poll?: number | 'auto'
wait?: number | 'auto'
}): void
}vi.setConfig({ testTimeout }) continues to work but the new API is preferred for timeout-only changes.
Alternative
No response
Additional context
No response
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that requests the same feature to avoid creating a duplicate.
Sub-issues
Collapse Sub-issuesSub-issues
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsApproved
Activity
sheremet-va commentedon Feb 26, 2026
As a note, we should probably also migrate to an ever-increasing interval instead of defining a single one and get rid of
expect.poll.interval:hi-ogawa commentedon Feb 27, 2026
I was also about to suggest budget/min based adjustment for browser, but I'm not sure if this needs to exposed explicitly. I'd expect this
mintrick is only internal mechanism to surface better error purely for DX to fail a moment before test timeout. So, users should be able to still bump the default action/assertion level timeout explicitly but still benefit from the budge/min adjustment.What I was thinking is to apply this logic always without specific "auto" config:
AriPerkkio commentedon Feb 27, 2026
Maybe also supporting dynamic timeout changing during test run. Currently
vi.setConfig()affects only tests that haven't started.nstepien commentedon Mar 21, 2026
It'd also be nice to unify error messages around timeouts to explain: what timed out, after how much time, what is the configured timeout, and what setting controls this timeout.
Maybe something like this
8 remaining items
hi-ogawa commentedon Jun 24, 2026
Just realized
expect.pollalready breaks in concurrent case and requires local context, that means ALS isn't technically necessary since it can pull the correct test time budget from context. https://stackblitz.com/edit/vitest-dev-vitest-lwdirte1?file=test%2Frepro.test.tsRelying on ALS for this logic would mean we also partly relax local context requirement, but I suggest we still keep the nuance to encourage local expect for concurrent in doc. We current say
Snapshots and Assertions must use expect from the local [Test Context](https://main.vitest.dev/guide/test-context.html) to ensure the right test is detected.https://main.vitest.dev/api/test.html#test-concurrentThe genuine new feature with ALS would be about timeout budget for
viAPI.hi-ogawa commentedon Jun 26, 2026
I spent some time to digest the overall direction. There doesn't seem to be enough context and fully actionable plan yet above, so I've summarized my plan below. A bit of repetition but wanted to clarify the scope of my first PR and also list the things I still want some clarifications.
Plan
Unified
timeoutconfig namespacetestTimeout→timeout.test,expect.poll.{timeout,interval}→timeout.poll, etc.).intervalis exposed only for user-predicate polling (poll -> expect.poll,wait -> vi.waitFor/waitUntil), not foraction— matching Playwright (locator actions / web-first assertions are{ timeout }-only;intervalsonly onexpect.poll/toPass) and existing Vitest behavior (locatorfindElementuses an internal hard-coded backoff, exposing onlytimeout). That's whyactionis a scalar whilepoll/waitallow the object form.vi.setTimeout(ms | { test, hook, action, poll, wait })as a focused shorthand overvi.setConfig.This directly resolves the sub-issues: #9157, #9741, #8308, and #10136 (per-call clamp surfaces the real error before the test timer — supersedes #10137).
Crucial logic: always-on budget clamp
The core idea (from the comment above) is to apply the budget clamp always as an internal DX mechanism, rather than gating it behind an default
'auto'case:configValue = 'auto'(the default) = ride the remaining test budget (like Playwright'sactionTimeout: 0, but named explicitly).configValue = number= a fixed cap below the budget. This is an important lever, not just an edge case: since'auto'rides the full test budget, a failing op waits out the whole budget before erroring — so configuring a shorter timeout (e.g.timeout.poll: 1000) lets you bail early and iterate faster. It's a deliberate DX choice between "wait as long as the test allows" ('auto') and "fail fast" (a number).{ timeout }is also clamped to the budget (this is the key change vs today'sprocessTimeoutOptions, which early-returns when a per-call timeout is set — and is why #10136 currently surfaces a generic "test timed out" instead of the actualexpect.pollerror).This generalizes the existing browser-only clamp (
processTimeoutOptions) toexpect.pollandvi.waitFor/waitUntilas well, and it already covers the hook case: the budget is read from the currently-executing test or hook (soexpect.element/locator actions inbeforeEachalready clamp tohookTimeouttoday — we just make this intentional and uniform).Worth being explicit that the clamp is a behavior change in itself — separate from the
'auto'default and even with an exact budget. The effective op timeout becomesmin(remaining budget − BUFFER, configured), so the− BUFFERshortens it near the deadline: an op (even with an explicit{ timeout }) that would have barely completed in the final ~BUFFERms before the test/hook deadline now failsBUFFER-early. It only affects tests already passing at the very timeout edge (extremely fragile), and the trade is a descriptive, source-mapped error instead of a generic "test timed out" — but I'll call it out as a breaking note, not just the default change.Additionally, following the suggestion #9751 (comment), the error message can show both the effective and configured timeout, and note when the op was clamped by the remaining test budget:
Concurrency & AsyncLocalStorage
The budget comes from the current execution context (
_currentTaskStartTime/_currentTaskTimeout), which are shared on the runner — so under concurrent tests they're ambiguous. The "existing bug" section proposes AsyncLocalStorage to fix this. The approach I'm proposing avoids ALS: guard the lookup withgetRunningTests().length, and when>= 2concurrent tests are detected, skip the clamp and fall back to the configured fixed timeout — exactly the "skip + fixed fallback" the issue already proposes for the browser case, applied uniformly to node + browser.This is best-effort under concurrency by construction (Playwright is exact only because it runs tests serially per worker). ALS would make the node-concurrency budget exact (and could separately fix global-
expecttest-binding), but it's a heavier, independent change. Whether to ship best-effort now or invest in ALS is a decision below — and it's coupled with the'auto'default: with no ALS,'auto'ops silently fall back to the fixed timeout under concurrent tests.Decisions not fully settled
From the above, extracting the decisions that still need a call:
action/poll/wait:'auto'everywhere, or keeppoll/waitat the historical fixed1000?: probably keeppollandwaitdefault.=> ✅ decision: go with
1000#1. With no ALS, the budget is ambiguous under concurrent tests, so we fall back to the fixed timeout; ALS would make it exact in node.=> ✅ decision: intergate ALS. just for tracking timeout mechanism. defer larger change of loosening local test context requirement.
poll/wait— how to exposeintervalalongside the timeout. Since these poll user code,intervalshould stay configurable globally; butintervalisn't a timeout, so it can't live cleanly in thetimeoutnamespace on its own. Splitting it (timeout.poll+expect.poll.interval) is incoherent, so I'm proposing the object formtimeout.poll: number | 'auto' | { timeout?, interval? }(mirrors the existing per-call options{ timeout, interval }). The awkward part is the nestedtimeout.poll.timeoutin the object form — acceptable since it only appears when you set an interval, but flagging it. (actionstays a scalar — no interval, matching Playwright + locator internals.)=> ✅ decision: per-call
intervals: number[]override only.Follow-up issues
Some related issues will be tackled separately. The following issues are to be created as follow-ups:
timeoutconfig namespace +vi.setTimeout+ docs (PR2).vi.setTimeoutextends the running test by re-arming its deadline). Playwright has prior art (testInfo.setTimeoutmutates the active slot live); fairly complex but considered doable.'auto', so breakpoints don't fail tests. The VS Code extension would flip it on debug.interval: number→intervals: number[]and tune the default curve (may land together with the above).FixtureOptions.timeout) / fixture setup excluded from the test budget (Fixture startup time is included in the first test which asks for it. #9303).expectlimitation in docs (.resolves/.rejects/.soft/snapshots/poll all bind to the current test).sheremet-va commentedon Jun 26, 2026
I wonder if we should always apply
Math.min(restOfTest, userTimeout), whereuserTimeoutis the number specified in the config/test andrestOfTestis the time until the test is finished. I think we can then keep it a 1000 by default.hi-ogawa commentedon Jun 26, 2026
Yes, what I mean is that
poll: 1000(default) still meansMath.min(budget - buffer, 1000).poll: autowould mean thenMath.min(budget - buffer, Infinity) = budget - buffer.hi-ogawa commentedon Jun 26, 2026
To be decided: whether "interval" should be configurable or we can hard-code something around 50ms. Check actual usage in the wild somehow.
hi-ogawa commentedon Jun 29, 2026
Continuing on #9751 (comment), I've searched GitHub to see how "interval" is actually used in the wild. There are some false positives but basic stats are following:
vi.waitFor+interval:expect.poll+interval:vi.waitUntil+interval:toPass+intervals:(Playwright array)expect.poll+intervals:(Playwright array)path:vitest.config.ts+interval:path:playwright.config.ts+intervals:Based on this, I can see there's a significant enough case to keep the
intervaloverride on a per-call basis. The main use cases are:interval: 0wants the fastest retry, so it re-polls immediately to minimize wasted time between checks when the predicate is cheap and you want the result as soon as it is ready.On the other hand, the global config
intervalis barely used (single digits), so it does not justify a config surface. Playwright's equivalent global knob is just as rare.So for the first PR, I'm going to implement:
interval: numbertointervals: number[](ascending backoff).intervalsto[0, 25, 50, 100, 250, 500](or whatever sensible)intervalsoverride.intervalsfor global config, sopollandwaitstay plain scalars instead of the awkward object form:sheremet-va commentedon Jun 29, 2026
This looks good to me 👍
hi-ogawa commentedon Jul 1, 2026
Found another oddball. There's
browser.expect.toMatchScreenshot.timeoutand also timeout/retry mechanism baked inexpect(...).toMatchScreenshot()where retry interval is effectively zero. Should this timeout logic unified in the same way? i.e.browser.expect.toMatchScreenshot.timeout(current default is 5000) in favor oftimeout.action(default auto)intervalsyet, so keep effective zero backoff.I'm going with the above direction, so please comment if have other opinions.
sheremet-va commentedon Jul 1, 2026
@macarie what do you think? I am not sure if
toMatchScreenshotshould followactionsince it's not an action 🤔 It's more of apolltimeoutmacarie commentedon Jul 1, 2026
I'm not sure either, this value is only used when trying to capture a stable screenshot, so technically it could be considered a
pollI believe.Maybe
timeoutis a bit of a misleading name and we could change it to something else. As is, this assertion does not have a real timeout, so we could introduce one.The internal retry interval logic should be considered an implementation detail tho, so I would not expose an option for that or make it configurable in any way — for now at least.
hi-ogawa commentedon Jul 2, 2026
Then the fate of
toMatchScreenshotis eitherbrowser.expect.toMatchScreenshot.timeout(default is 5000)browser.expect.toMatchScreenshot.timeoutand usetimeout.action(default auto)browser.expect.toMatchScreenshot.timeoutand usetimeout.poll(default 1000)The 3rd seems no go since it makes default too short.
A few notes:
expect.element(locator).toMatchScreenshot()usestimeout.actionbased polling forlocatorexistence first, then goes totoMatchScreenshotpolling separately once.expect.element(locator).toMatchAriaSnapshot()usestimeout.actionbased polling forlocatorexistence first, then goes topollMatchDomainwhich also uses sametimeout.action-based timeout.I'm still opting for unifying to
timeout.action.sheremet-va commentedon Jul 2, 2026
I feel like using timeout.action introduces more inconsistencies. If we start treating it as „anything in the browser“, then it starts to loose its point. In my opinion, actions are only the methods on the locator
hi-ogawa commentedon Jul 3, 2026
Discussed in the meeting:
timeout.actionoption since naming can be misleading. Alternative idea is to addtimeout.browserand support object union style to refine:We may tweak
timeout.poll/wait: 1000default value on browser, just like we tweaktest/hook. Perhaps totimeout.poll/wait: 5000.expect.toMatchScreenshot.timeout's value5000are arbitrary. It's fine to subsumed to somewhere else with a different value.For error message improvement, we can probe playwright timeout error and patch message.
test: make the test timeouts explicit and bound the worker pool (#251)