Skip to content

Unify and simplify timeout configuration #9751

Open
1 of 5 issues completed
Open

Description

@sheremet-va

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:

  1. expect.element().toBeVisible() uses expect.poll.timeout, but users don't know this because expect.element feels like a browser action, not a poll.
  2. page.getByRole('button').click() uses actionTimeout, but only in Playwright — it's buried under browser.providerOptions.actionTimeout, making it provider-specific for what should be a framework-level concept.
  3. Hidden dynamic adjustment: In browser mode, both expect.element and locator actions secretly compute their timeout from testTimeout - elapsedTime - 100ms (see processTimeoutOptions in packages/browser/src/client/tester/tester-utils.ts). This fires the action timeout before testTimeout to produce better stack traces. Users are unaware this happens.
  4. Timeouts are scattered across the config: testTimeout is top-level, expect.poll.timeout is nested under expect, actionTimeout is under browser.providerOptions — there's no single place to see and reason about all timeouts.
  5. vi.waitFor / vi.waitUntil defaults 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

Sub-issues

Sub-issues

1 of 5 Issues completed
Loading 5 sub-issues

Activity

  1. added
    p2-to-be-discussed
    on Feb 26, 2026
  2. moved this to P2 - 5 in Team Boardon Feb 26, 2026
  3. sheremet-va commented on Feb 26, 2026

    @sheremet-va
    MemberAuthor

    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:

    await expect.poll(() => val()).toBe(1)
    // 0, 20, 50, 100, 100, 200, 500
  4. hi-ogawa commented on Feb 27, 2026

    @hi-ogawa
    Collaborator

    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 min trick 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:

    effective_timeout = min(
      startTime + timeout.test - now() - buffer,
      <per-call timeout> || <timeout from config> || Infinity
    )
  5. AriPerkkio commented on Feb 27, 2026

    @AriPerkkio
    Member

    Maybe also supporting dynamic timeout changing during test run. Currently vi.setConfig() affects only tests that haven't started.

    test("example", async () => {
      // Remaining test time - action time for these:
      await expect.element(page.getByText('')).toBeInTheDocument()
      await expect.element(page.getByText('')).toBeInTheDocument()
    
      // Ok we reached over here. Let's increase test timeout for next slow actions
      vi.setTimeout(30_000);
      await expect.element(page.getByText('')).toBeInTheDocument()
      await expect.element(page.getByText('')).toBeInTheDocument()
    });
  6. moved this from P2 - 5 to Approved in Team Boardon Feb 27, 2026
  7. added
    p2-nice-to-have
    and removed
    p2-to-be-discussed
    on Feb 27, 2026
  8. nstepien commented on Mar 21, 2026

    @nstepien
    Contributor

    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

    TimeoutError: test timed out after 2123ms (with local timeout: 2000ms)
    TimeoutError: test timed out after 2123ms (with global test.timeout.test: 2000ms)
    TimeoutError: expect.poll() timed out after 2123ms (with local timeout: 2000ms)
    TimeoutError: expect.poll() timed out after 2123ms (with global test.timeout.poll: 2000ms)
    
  9. 8 remaining items

  10. hi-ogawa commented on Jun 24, 2026

    @hi-ogawa
    Collaborator

    Just realized expect.poll already 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.ts

    import { test, expect } from 'vitest';
    
    test.describe('poll', () => {
      test.concurrent('a', async () => {
        await new Promise((r) => setTimeout(r, 100));
        await expect.poll(() => 1).toBe(1);
        // 🔥🔥 Error: expect.poll() must be called inside a test
      });
    
      test.concurrent('b', async () => {});
    });
    
    test.describe('soft', () => {
      test.concurrent('a', async () => {
        await new Promise((r) => setTimeout(r, 100));
        expect.soft(1).toBe(1);
        // 🔥🔥 Error: expect.soft() can only be used inside a test
      });
    
      test.concurrent('b', async () => {});
    });

    Relying 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-concurrent

    The genuine new feature with ALS would be about timeout budget for vi API.

  11. hi-ogawa commented on Jun 26, 2026

    @hi-ogawa
    Collaborator

    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 timeout config namespace

    test: {
      timeout: {
        test: 5_000,       // was testTimeout       (number)
        hook: 10_000,      // was hookTimeout       (number)
        teardown: 10_000,  // was teardownTimeout   (number)
        action: 'auto',    // browser actions / locators / expect.element  (number | 'auto')
        poll: 'auto',      // was expect.poll.timeout   (number | 'auto' | { timeout?, interval? })
        wait: 'auto',      // vi.waitFor / vi.waitUntil  (number | 'auto' | { timeout?, interval? })
      },
    }
    • Old flat names become deprecated aliases (testTimeout → timeout.test, expect.poll.{timeout,interval} → timeout.poll, etc.).
    • interval is exposed only for user-predicate polling (poll -> expect.poll, wait -> vi.waitFor/waitUntil), not for action — matching Playwright (locator actions / web-first assertions are { timeout }-only; intervals only on expect.poll/toPass) and existing Vitest behavior (locator findElement uses an internal hard-coded backoff, exposing only timeout). That's why action is a scalar while poll/wait allow the object form.
    • vi.setTimeout(ms | { test, hook, action, poll, wait }) as a focused shorthand over vi.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:

    effective = min(
      currentContextDeadline - now() - BUFFER,   // remaining budget (test OR hook)
      perCall ?? configValue ?? Infinity          // the cap; 'auto' => Infinity (no cap)
    )
    
    • configValue = 'auto' (the default) = ride the remaining test budget (like Playwright's actionTimeout: 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).
    • A per-call { timeout } is also clamped to the budget (this is the key change vs today's processTimeoutOptions, which early-returns when a per-call timeout is set — and is why #10136 currently surfaces a generic "test timed out" instead of the actual expect.poll error).

    This generalizes the existing browser-only clamp (processTimeoutOptions) to expect.poll and vi.waitFor/waitUntil as well, and it already covers the hook case: the budget is read from the currently-executing test or hook (so expect.element/locator actions in beforeEach already clamp to hookTimeout today — 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 becomes min(remaining budget − BUFFER, configured), so the − BUFFER shortens it near the deadline: an op (even with an explicit { timeout }) that would have barely completed in the final ~BUFFER ms before the test/hook deadline now fails BUFFER-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:

    # fails at its configured timeout
    expect.poll() timed out in 1000ms (test.timeout.poll)
    
    # clamped: configured timeout was larger than the remaining test budget
    expect.poll() timed out in 1900ms — capped by remaining test time
      (configured test.timeout.poll: 10000ms, test.timeout.test: 2000ms)
    

    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 with getRunningTests().length, and when >= 2 concurrent 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-expect test-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:

    1. Default for action/poll/wait: 'auto' everywhere, or keep poll/wait at the historical fixed 1000?: probably keep poll and wait default.
      => ✅ decision: go with 1000
    2. Concurrency: best-effort (no ALS) vs ALS for exactness — coupled with #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.
    3. Config shape for poll/wait — how to expose interval alongside the timeout. Since these poll user code, interval should stay configurable globally; but interval isn't a timeout, so it can't live cleanly in the timeout namespace on its own. Splitting it (timeout.poll + expect.poll.interval) is incoherent, so I'm proposing the object form timeout.poll: number | 'auto' | { timeout?, interval? } (mirrors the existing per-call options { timeout, interval }). The awkward part is the nested timeout.poll.timeout in the object form — acceptable since it only appears when you set an interval, but flagging it. (action stays 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:

    • Phase 1 (this issue) — always-on budget clamp + unified error messages (PR1), then the timeout config namespace + vi.setTimeout + docs (PR2).
    • Follow-up — dynamic mid-test timeout (vi.setTimeout extends the running test by re-arming its deadline). Playwright has prior art (testInfo.setTimeout mutates the active slot live); fairly complex but considered doable.
    • Follow-up — don't fire timeouts while debugging/inspecting (test timeout overwrite also applied when debugging #6950): a special (likely internal) mode that overrides any timeout — config, per-call, explicit — into infinity / 'auto', so breakpoints don't fail tests. The VS Code extension would flip it on debug.
    • Follow-up — ascending poll interval / backoff: generalize interval: number → intervals: number[] and tune the default curve (may land together with the above).
    • Follow-up — per-fixture timeout (FixtureOptions.timeout) / fixture setup excluded from the test budget (Fixture startup time is included in the first test which asks for it. #9303).
    • Follow-up (side note) — clarify the concurrent + global-expect limitation in docs (.resolves/.rejects/.soft/snapshots/poll all bind to the current test).
  12. sheremet-va commented on Jun 26, 2026

    @sheremet-va
    MemberAuthor

    Default for action/poll/wait: 'auto' everywhere, or keep poll/wait at the historical fixed 1000?: probably keep poll and wait default.

    I wonder if we should always apply Math.min(restOfTest, userTimeout), where userTimeout is the number specified in the config/test and restOfTest is the time until the test is finished. I think we can then keep it a 1000 by default.

  13. hi-ogawa commented on Jun 26, 2026

    @hi-ogawa
    Collaborator

    Default for action/poll/wait: 'auto' everywhere, or keep poll/wait at the historical fixed 1000?: probably keep poll and wait default.

    I wonder if we should always apply Math.min(restOfTest, userTimeout), where userTimeout is the number specified in the config/test and restOfTest is the time until the test is finished. I think we can then keep it a 1000 by default.

    Yes, what I mean is that poll: 1000 (default) still means Math.min(budget - buffer, 1000). poll: auto would mean then Math.min(budget - buffer, Infinity) = budget - buffer.

  14. hi-ogawa commented on Jun 26, 2026

    @hi-ogawa
    Collaborator

    To be decided: whether "interval" should be configurable or we can hard-code something around 50ms. Check actual usage in the wild somehow.

  15. hi-ogawa commented on Jun 29, 2026

    @hi-ogawa
    Collaborator

    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:

    search ~hits
    vi.waitFor + interval: ~3,100
    expect.poll + interval: ~450
    vi.waitUntil + interval: ~180
    toPass + intervals: (Playwright array) ~1,770
    expect.poll + intervals: (Playwright array) ~1,680
    path:vitest.config.ts + interval: single digits (some are false positives)
    path:playwright.config.ts + intervals: single digits

    Based on this, I can see there's a significant enough case to keep the interval override on a per-call basis. The main use cases are:

    • Longer timeout wants a longer interval, because when the budget is large (polling something slow or external) people deliberately widen the interval to avoid hammering it.
    • interval: 0 wants 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 interval is 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:

    • Change per-call interval: number to intervals: number[] (ascending backoff).
    • Default intervals to [0, 25, 50, 100, 250, 500] (or whatever sensible)
    • Keep the per-call intervals override.
    • No intervals for global config, so poll and wait stay plain scalars instead of the awkward object form:
    test: {
      timeout: {
        ...
        poll: 1_000,   // number | 'auto'  (no { timeout, interval } object)
        wait: 1_000,   // number | 'auto'
      },
    }
  16. sheremet-va commented on Jun 29, 2026

    @sheremet-va
    MemberAuthor

    So for the first PR, I'm going to implement:

    This looks good to me 👍

  17. hi-ogawa commented on Jul 1, 2026

    @hi-ogawa
    Collaborator

    Found another oddball. There's browser.expect.toMatchScreenshot.timeout and also timeout/retry mechanism baked in expect(...).toMatchScreenshot() where retry interval is effectively zero. Should this timeout logic unified in the same way? i.e.

    • remove browser.expect.toMatchScreenshot.timeout (current default is 5000) in favor of timeout.action (default auto)
    • clamp timeout by remaining time.
    • don't introduce own intervals yet, so keep effective zero backoff.

    I'm going with the above direction, so please comment if have other opinions.

  18. sheremet-va commented on Jul 1, 2026

    @sheremet-va
    MemberAuthor

    @macarie what do you think? I am not sure if toMatchScreenshot should follow action since it's not an action 🤔 It's more of a poll timeout

  19. macarie commented on Jul 1, 2026

    @macarie
    Member

    I'm not sure either, this value is only used when trying to capture a stable screenshot, so technically it could be considered a poll I believe.

    Maybe timeout is 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.

  20. hi-ogawa commented on Jul 2, 2026

    @hi-ogawa
    Collaborator

    Then the fate of toMatchScreenshot is either

    • keep browser.expect.toMatchScreenshot.timeout (default is 5000)
    • remove browser.expect.toMatchScreenshot.timeout and use timeout.action (default auto)
    • remove browser.expect.toMatchScreenshot.timeout and use timeout.poll (default 1000)

    The 3rd seems no go since it makes default too short.

    A few notes:

    • regardless of which to choose, we'll have auto timeout clamp based on remaining time.
    • expect.element(locator).toMatchScreenshot() uses timeout.action based polling for locator existence first, then goes to toMatchScreenshot polling separately once.
    • expect.element(locator).toMatchAriaSnapshot() uses timeout.action based polling for locator existence first, then goes to pollMatchDomain which also uses same timeout.action-based timeout.

    I'm still opting for unifying to timeout.action.

  21. sheremet-va commented on Jul 2, 2026

    @sheremet-va
    MemberAuthor

    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

  22. hi-ogawa commented on Jul 3, 2026

    @hi-ogawa
    Collaborator

    Discussed in the meeting:

    • We want to move away from timeout.action option since naming can be misleading. Alternative idea is to add timeout.browser and support object union style to refine:
    timeout: {
      ...,
      browser: number | 'auto' | {
        element: ..., (e.g. expect.element, findElement),
        action: ..., (e.g. userEvent/locator.click etc.),
        screenshot: ... (maybe)
      },
    }
    • We may tweak timeout.poll/wait: 1000 default value on browser, just like we tweak test/hook. Perhaps to timeout.poll/wait: 5000.

    • expect.toMatchScreenshot.timeout's value 5000 are 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.

  23. removed this from the 5.0.0 milestone on Aug 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

p2-nice-to-have

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions