| | |

Vitest 20 🧪 Concurrent Tests — test.concurrent and Parallel Execution

⏱️ Estimated read: 9 min | |

Vitest has two levels of parallelism, and they are controlled by different mechanisms. At the file level, Vitest runs test files in parallel across worker processes by default, and the fileParallelism and maxWorkers options control that. At the test level, the tests inside a single file run sequentially by default, and the concurrent modifier is the opt-in that runs them together with Promise.all. The distinction matters because the two levels have different trade-offs: file parallelism is the main driver of a suite’s speed, and test-level concurrency only helps when the tests spend their time waiting on asynchronous operations .

This chapter covers the test.concurrent modifier, the describe.concurrent block form, and the maxConcurrency limit that bounds the number of simultaneously running tests. The sections that follow walk through the modifier, the opt-out pattern that keeps a shared-resource test sequential, and the hook behavior that changes when the tests overlap.

Key point: test.concurrent runs the marked tests in the same file together with Promise.all, bounded by maxConcurrency; it only speeds up tests that await something, because Vitest does not create extra workers for them, and a test that uses a shared resource opts out with { concurrent: false }.


a. The test.concurrent modifier and the Promise.all grouping

test.concurrent marks a single test as concurrent. Vitest groups the concurrent tests in the same file and runs them together with Promise.all, and the number of tests running at once is bounded by the maxConcurrency option .

import { test, expect } from "vitest";

test.concurrent("fetches user profile", async () => {
  const user = await fetchUser(1);
  expect(user.name).toBe("Alice");
});

test.concurrent("fetches user posts", async () => {
  const posts = await fetchPosts(1);
  expect(posts).toHaveLength(3);
});

The modifier is the opt-in because the default is sequential. The tests inside a file share setup and state through the lifecycle hooks, and the sequential order is the safest default for that sharing. The concurrent modifier is the declaration that the tests are independent and can overlap .

The describe.concurrent block is the suite-level form. The callback’s tests are all concurrent, and the block is the way to mark a group without repeating the modifier on every test.

import { describe, test, expect } from "vitest";

describe.concurrent("user API", () => {
  test("fetches profile", async () => {
    const user = await fetchUser(1);
    expect(user.name).toBe("Alice");
  });

  test("fetches posts", async () => {
    const posts = await fetchPosts(1);
    expect(posts).toHaveLength(3);
  });
});

The sequence.concurrent: true config option makes every test in the project concurrent by default. The individual test or suite opts out with { concurrent: false } when it needs the sequential order .


b. When concurrency actually helps

The performance gain is conditional. Vitest does not create extra workers for the concurrent tests; they all run in the same worker as the file they belong to. The concurrency is the Promise.all interleaving, which means a test that spends its time awaiting a network request, a timer, or a file read can overlap with another test that is also waiting. A purely synchronous test blocks the single JavaScript thread, and the concurrent modifier does not change that .

// These run one after another despite `concurrent`,
// because there is nothing to await
test.concurrent("the first test", () => {
  expect(1).toBe(1);
});

test.concurrent("the second test", () => {
  expect(2).toBe(2);
});

The rule is mechanical: the concurrent modifier is worth adding when the test’s body contains an await that waits on an external resource. A test that awaits a fetch, a setTimeout, a database query, or a file read benefits. A test that asserts on a pure function does not, and the modifier adds the overhead of the Promise.all grouping for no gain.

The file-level parallelism is the bigger lever. The fileParallelism: true default runs the test files across workers, and the maxWorkers option controls how many run at once. A suite with many files gets the most speed from the file-level parallelism, and the concurrent modifier is the second-level optimization for a file whose tests are individually slow .


c. The opt-out and the hook behavior

A test that uses a shared resource—a database row, a file, a server—must not run concurrently with the test that mutates the same resource. The { concurrent: false } option opts the test out of the inherited concurrency, and the describe block with the same option opts out the whole suite .

describe.concurrent("mostly parallel", () => {
  test("parallel 1", async () => { ... });

  // Opt this test out of the inherited concurrency
  test("must run alone", { concurrent: false }, async () => {
    await mutateSharedResource();
  });
});

The hook behavior changes when the tests run concurrently. The beforeAll and afterAll hooks still run once for the group, but the beforeEach and afterEach hooks run for each test and may overlap, because the tests themselves overlap. The sequence.hooks option controls the hook order, and the "parallel" value runs the hooks concurrently within the maxConcurrency limit .

The expect from the test context is the recommendation for concurrent tests. The import { expect } from "vitest" works, but the context’s expect is the instance the test should use for snapshots and the per-test state .

test.concurrent("uses context expect", async ({ expect }) => {
  expect(await fetchValue()).toBe("result");
});

The test.sequential and describe.sequential forms were removed in Vitest 5. The replacement is the { concurrent: false } option, which is the same behavior with the option syntax .


Complete Example Session

// ============================================
// PART 1: THE CONCURRENT TESTS
// ============================================
import { test, expect, describe } from "vitest";

describe.concurrent("user API", () => {
  test("fetches profile", async () => {
    const user = await fetchUser(1);
    expect(user.name).toBe("Alice");
  });

  test("fetches posts", async () => {
    const posts = await fetchPosts(1);
    expect(posts).toHaveLength(3);
  });
});

// ============================================
// PART 2: THE OPT-OUT
// ============================================
describe.concurrent("mostly parallel", () => {
  test("parallel", async () => { ... });

  test("must run alone", { concurrent: false }, async () => {
    await mutateSharedResource();
  });
});

// ============================================
// PART 3: THE CONFIG
// ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    maxConcurrency: 5, // bound the concurrent tests per file
  },
});

// ============================================
// PART 4: THE SYNC TEST (NO BENEFIT)
// ============================================
test.concurrent("sync test", () => {
  expect(1).toBe(1); // runs sequentially; concurrent adds no speed
});

The parts covered the concurrent tests, the opt-out, the maxConcurrency config, and the synchronous test that does not benefit.


Quick Reference

Concurrency Forms

FormEffect
test.concurrent(name, fn)One concurrent test
describe.concurrent(name, fn)All tests in the block concurrent
{ concurrent: false }Opt out of inherited concurrency
sequence.concurrent: trueAll tests concurrent by default

Limits and Hooks

OptionEffect
maxConcurrencyMax tests running at once
sequence.hooks: "parallel"Concurrent hooks
beforeAll / afterAllOnce per group
beforeEach / afterEachPer test, may overlap

The Two Parallelism Levels

LevelKnobControls
FilesfileParallelism, maxWorkersWorker processes
Teststest.concurrentTests within one file

Best Practices

✅ Do This:

// Use concurrent for async tests
test.concurrent("fetches", async () => { await fetch(); });   // ✅

// Use the suite form for a group
describe.concurrent("api", () => { ... });                     // ✅

// Opt out for a shared resource
test("mutates", { concurrent: false }, async () => { ... });   // ✅

// Bound the concurrency
maxConcurrency: 5                                              // ✅

❌ Don’t Do This:

// Mark a synchronous test concurrent
test.concurrent("sync", () => { expect(1).toBe(1); });         // ❌

// Share a resource across concurrent tests
test.concurrent("writes", async () => { await db.insert(); }); // ❌

// Assume concurrent creates workers
// (it does not)                                              // ❌

Common Pitfalls

PitfallWhy It HappensFix
No speed gainSynchronous testRemove concurrent
Flaky shared stateConcurrent tests share a resource{ concurrent: false }
Hook overlapbeforeEach runs concurrentlysequence.hooks: "stack"
Snapshot mismatchGlobal expect usedContext expect

Real-World Examples

1. Concurrent test

test.concurrent("fetches", async () => { ... });

2. Concurrent suite

describe.concurrent("api", () => { ... });

3. Opt out

test("mutates", { concurrent: false }, async () => { ... });

4. Global default

test: { sequence: { concurrent: true } }

5. Max concurrency

test: { maxConcurrency: 5 }

6. Context expect

test.concurrent("x", async ({ expect }) => { ... });

7. Async fetch

await fetchUser(1); // benefits from concurrent

8. Sync test

test.concurrent("sync", () => { expect(1).toBe(1); }); // no gain

9. File parallelism

test: { fileParallelism: true }

10. Workers

test: { maxWorkers: 4 }

Visual

The Two Parallelism Levels

┌─────────────────────────────────────────────────────────┐
│  FILE LEVEL                                             │
│  test file A ──► worker 1                               │
│  test file B ──► worker 2                               │
│  test file C ──► worker 3                               │
│                                                         │
│  TEST LEVEL (within one file)                           │
│  test 1 ──┐                                             │
│  test 2 ──┼──► Promise.all (same worker)                │
│  test 3 ──┘                                             │
└─────────────────────────────────────────────────────────┘

When Concurrent Helps

┌─────────────────────────────────────────────────────────┐
│  ASYNC TEST                    SYNC TEST                │
│  await fetch()                 expect(1).toBe(1)        │
│  await timer()                                          │
│         │                             │                 │
│         ▼                             ▼                 │
│  overlaps with others          blocks the thread        │
│  speed gain                    no gain                  │
└─────────────────────────────────────────────────────────┘

The Opt-Out

┌─────────────────────────────────────────────────────────┐
│  describe.concurrent("mostly parallel", () => {         │
│    test("parallel", async () => { ... });               │
│                                                         │
│    test("must run alone", { concurrent: false }, async () => {│
│      await mutateSharedResource();                      │
│    });                                                  │
│  });                                                    │
└─────────────────────────────────────────────────────────┘

Hook Behavior

┌─────────────────────────────────────────────────────────┐
│  CONCURRENT TESTS                                       │
│  beforeAll  → once for the group                        │
│  beforeEach → per test, may overlap                     │
│  afterEach  → per test, may overlap                     │
│  afterAll   → once for the group                        │
│                                                         │
│  sequence.hooks: "parallel" → hooks also overlap        │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Test modifiertest.concurrent
Suite modifierdescribe.concurrent
Opt-out{ concurrent: false }
BoundmaxConcurrency
Global defaultsequence.concurrent: true
BenefitOnly for tests that await
Hook ordersequence.hooks

Key takeaways:

  • test.concurrent runs the marked tests together with Promise.all. The tests share the file’s worker, and the number running at once is bounded by maxConcurrency .
  • The speed gain is conditional. A test that awaits a network request, a timer, or a file read can overlap with another waiting test. A synchronous test blocks the single thread, and the modifier does not change that .
  • The opt-out is { concurrent: false }. A test that uses a shared resource must not overlap with the test that mutates it, and the option is the way to keep it sequential while the rest of the block runs concurrently .
  • The hook behavior changes. beforeAll and afterAll still run once per group, but beforeEach and afterEach run per test and may overlap. The sequence.hooks: "parallel" option makes the hooks themselves concurrent .
  • The test.sequential form was removed in Vitest 5. The replacement is the { concurrent: false } option, which is the same behavior with the option syntax .

Remember: The concurrency modifier is for the test that waits. Add it to the tests that await an external resource, leave the synchronous tests sequential, and opt out the test that shares a resource. The file-level parallelism is the bigger lever for a suite’s speed, and the test-level concurrency is the second-level optimization for the file whose tests are individually slow.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!