Workers SDK Issue Reports

← Back to Dashboard

#10201 `vi.mock()` not working with `cloudflare:test` setup file imports

Recommendation:KEEP OPEN
Difficulty:easy
Reasoning:

Confirmed bug. Maintainer vicb identified fix (add vi.resetModules() to onBeforeRunFiles) but not yet implemented. Workaround: call vi.resetModules() before mocking.

Suggested Action:

Implement proposed fix in test-runner.ts onBeforeRunFiles()

Analysis Report

Issue Review: cloudflare/workers-sdk#10201

Summary

vi.mock() calls are not applied when vitest setup file imports from cloudflare:test.

Findings

  • Created: 2025-08-03
  • Updated: 2025-10-13
  • Version: @cloudflare/vitest-pool-workers 0.8.59 → 0.12.6 (current)
  • Component: vitest-pool-workers
  • Labels: bug
  • Comments: 2

Key Evidence

  • Bug confirmed by maintainer: vicb confirmed the issue and reproduced it on 2025-10-13
  • Workaround exists: Calling vi.resetModules() before setting up mocks resolves the issue
  • Proposed fix identified: Maintainer suggested adding vi.resetModules() to onBeforeRunFiles() in test-runner.ts
  • Fix NOT yet implemented: Current codebase (as of main branch) only has vi.resetModules() in onAfterRunFiles(), not in onBeforeRunFiles() where it needs to be added
  • Minimal reproduction available: https://github.com/jimmycallin/cloudflare-workers-d1-vitest-mock-issue
  • Related PR #8182 fixed a similar issue for watch mode but this is a different scenario (setup file imports)

Code Analysis

Current onBeforeRunFiles() in test-runner.ts (lines 213-225):

async onBeforeRunFiles() {
    if (DEBUG) {
        __console.log("onBeforeRunFiles");
        await scheduler.wait(100);
    }

    resetMockAgent(fetchMock);
    // @ts-expect-error Support Vitest v2
    if (super.onBeforeRunFiles) {
        // @ts-expect-error Support Vitest v2
        return super.onBeforeRunFiles();
    }
}

The proposed fix adds vi.resetModules() after resetMockAgent(fetchMock):

 resetMockAgent(fetchMock);
+vi.resetModules();

Recommendation

Status: KEEP OPEN

Reasoning: This is a confirmed bug with a clear reproduction and a known fix that has not been implemented. A maintainer has already identified the exact code change needed but no PR has been created to address it.

Action: The fix is straightforward - add vi.resetModules() to onBeforeRunFiles() in packages/vitest-pool-workers/src/worker/lib/cloudflare/test-runner.ts. A PR should be created to implement the fix proposed by vicb.

Notes & Feedback (0)

No notes yet.

Add Note