Skip to content

Track the current test with AsyncLocalStorage for concurrent tests #11875

Open
0 of 1 issue completed
Open

Description

@hi-ogawa

Note

Updated 2026-11-06: the problem is now sorted by whether the test context offers a working version, and the suggested solution starts as an opt-in.

Clear and concise description of the problem

Vitest tracks the current test in module-level globals, getCurrentTest() in the runner and getWorkerState().current for the current task, which the runner sets when each test starts. Anything that looks up the current test later gets whichever test started last. That's the wrong test whenever a test's code is still running after another test has started.

Case Affected APIs Works today through
🟦 APIs with no test context equivalent, in concurrent tests console output, vi.waitFor and vi.waitUntil trace steps, the test name on module errors, TestRunner.getCurrentTest() in library code nothing
🟪 APIs with a test context equivalent, in concurrent tests the global expect (.resolves, .rejects, expect.soft, expect.poll, snapshots, this.task in custom matchers), onTestFinished, onTestFailed context.expect, context.onTestFinished, context.onTestFailed
🟧 A test that timed out and keeps running, without test.concurrent both of the above the test context, for assertions only

🟦 APIs with no test context equivalent

These APIs find the test on their own, and users have nothing to switch to, so they can't work in concurrent tests today. A console.log after an await shows up under another test or the file (#9267), and so do logs from beforeAll and afterAll of concurrent sibling suites. The trace timeline skips vi.waitFor and vi.waitUntil steps while more than one test is running, and the per-test deadline from #9751 would need the current test in the same way. Library code, such as a helper that records artifacts, can't get its test without the user passing it in.

Example with console output

The log from a shows up under the file instead of under a, because b finished first and reset the current task:

import { test } from 'vitest'

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

test.concurrent('a', async () => {
  await sleep(20)
  console.log('log from a')
})

test.concurrent('b', async () => {
  await sleep(10)
  console.log('log from b')
})
stdout | repro.test.js > b
log from b

stdout | repro.test.js
log from a

🟪 APIs with a test context equivalent

These APIs have working versions on the test context, and the docs ask for them in concurrent tests for snapshots and expect.assertions. But the global versions look the same and quietly attach their work to another test, and most of these effects aren't documented. For example, a pending .resolves or .rejects is registered on whichever test getCurrentTest() returns, and that test waits for it when its own body returns and fails with its error.

Example with .resolves

Test b passes on its own, but fails with a's assertion error:

import { expect, test } from 'vitest'

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const fetchUser = async () => {
  await sleep(50)
  return { name: 'bob' }
}

test.concurrent('a', async () => {
  await sleep(10)
  // the global `expect` resolves to test 'b' here
  await expect(fetchUser()).resolves.toMatchObject({ name: 'alice' })
})

test.concurrent('b', async () => {
  await sleep(20)
})
 ❯ repro.test.js (2 tests | 2 failed) 71ms
   × a 70ms
   × b 70ms

 FAIL  repro.test.js > a
 FAIL  repro.test.js > b
AssertionError: expected { name: 'bob' } to match object { name: 'alice' }

🟧 Tests that time out

A test that times out keeps running in the background while the next test starts, so its late work goes to the next test. This happens without test.concurrent, and it affects both groups above. The test context covers its assertions, but not its console output.

Example with a timed-out test
import { expect, test } from 'vitest'

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const fetchUser = async () => {
  await sleep(200)
  return { name: 'bob' }
}

test('a', async () => {
  await sleep(100)
  // 'a' already timed out, so the global `expect` resolves to test 'b' here
  await expect(fetchUser()).resolves.toMatchObject({ name: 'alice' })
}, 50)

test('b', async () => {
  await sleep(100)
})
 ❯ repro.test.js (2 tests | 2 failed) 308ms
   × a 55ms
   × b 251ms

 FAIL  repro.test.js > a
Error: Test timed out in 50ms.

 FAIL  repro.test.js > b
AssertionError: expected { name: 'bob' } to match object { name: 'alice' }

Suggested solution

Run each test inside an AsyncLocalStorage context in Node, and make the internal lookups of the current test and the current task read that context first. Then both groups find the right test, under test.concurrent and after a test times out. The APIs without an equivalent start working, and the global APIs behave like the ones from the test context. Console output and module errors keep using getWorkerState().current outside a test, so output from beforeAll still goes to its suite.

Browser mode keeps today's behavior, because only Node workers back the runner's current-test lookup with AsyncLocalStorage. Code started by file- or worker-scoped fixtures, such as a server's request handlers, keeps the context of the test that first set the fixture up. The review note has the details for both.

On Node 22, AsyncLocalStorage runs on promise hooks, which makes test/unit about 22% slower and adds Node's internal symbols to every promise, which pretty-format prints. Node 24 builds it on AsyncContextFrame and shows no measurable cost. So the context can start as an (experimental?) opt-in, and become the default when Vitest drops Node 22. The first group is the reason to opt in, because nothing else fixes it. The docs keep asking for the test context's expect until the default changes.

Alternative

Keep the globals and skip ambiguous cases while several tests run, which is what the trace timeline does now. Users get correct results for the second group only through the test context, and the first group stays broken in concurrent tests.

Additional context

The same context can later carry more per-test state. These are separate follow-ups:

Activity

  1. added theissue type on Nov 4, 2026
  2. added
    p3-minor-bugAn edge case that only affects very specific usage (priority)
    on Nov 4, 2026
  3. added
    p2-to-be-discussedEnhancement under consideration (priority)
    and removed
    p3-minor-bugAn edge case that only affects very specific usage (priority)
    on Nov 4, 2026
  4. moved this to P2 - 4 in Team Boardon Nov 4, 2026
  5. moved this from P2 - 4 to P2 - 3 in Team Boardon Nov 4, 2026
  6. moved this from P2 - 3 to Discussing in Team Boardon Nov 6, 2026
  7. added
    p2-nice-to-haveNot breaking anything but nice to have (priority)
    and removed
    p2-to-be-discussedEnhancement under consideration (priority)
    on Nov 6, 2026
  8. moved this from Discussing to Approved in Team Boardon Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    p2-nice-to-haveNot breaking anything but nice to have (priority)

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions