Repository navigation
Description
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.
- review note https://gist.github.com/hi-ogawa/5da846997896e21a5f1c853883637d0a
- Related
- Automatic expect tracking for concurrent tests #5665
- Unify and simplify timeout configuration #9751 (per-test deadline for timeouts)
- Using `test.concurrent` causes test report to attribute console output incorrectly #9267
- feat(experimental): add trace timeline for node #11753, fix(experimental): skip ambiguous
expect.polltrace steps in concurrent tests #11869
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:
- the global
expectdelegating to the test's ownexpect, as Automatic expect tracking for concurrent tests #5665 suggests, which fixesexpect.assertions,expect.hasAssertions, andexpect.requireAssertionswith the globalexpect(requireAssertions,sequence.concurrentand mixeddescribenesting don't work together #8469). Until then these still need theexpectfrom the test context, because they count on one global state rather than per test. - the per-test deadline that Unify and simplify timeout configuration #9751 needs, which has the same problem today
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsApproved
Activity
fix(ci,test): corrige CI quebrado e flakiness intermitente na suíte d…