Skip to content

vi.mock() doesn't work if module is already imported #8246

@ocavue

Description

@ocavue

Describe the bug

When I run a test using the following mock code:

import { vi } from "vitest";

vi.mock("./random", () => {
  return {
    randomString: () => "__MOCK__",
  };
});

Vitest in browser mode isn't functioning properly.

I found a section in the documentation discussing Spying on browser mode, but I'm still unsure how to resolve my use case after reading it.

Reproduction

Git repo: https://github.com/issueset/vitest-mock-browser-mode

Reproduction steps:

❯ git clone https://github.com/issueset/vitest-mock-browser-mode
❯ cd vitest-mock-browser-mode
❯ pnpm install
❯ pnpm run test

> @vitest/example-test@ test /private/tmp/vitest-mock-browser-mode
> vitest run

 RUN  v3.2.4 /private/tmp/vitest-mock-browser-mode

 ✓ src/without-mock.test.ts (1 test) 1ms
 ✓ src/with-mock.test.ts (1 test) 1ms

❯ pnpm run test:browser

> @vitest/example-test@ test:browser /private/tmp/vitest-mock-browser-mode
> vitest run --config=vitest.browser.config.ts

 RUN  v3.2.4 /private/tmp/vitest-mock-browser-mode

Port 63315 is in use, trying another one...
 ❯  chromium  src/with-mock.test.ts (1 test | 1 failed) 3ms
   × randomString 2ms
     → expected '43587017925835303' to be '__MOCK__' // Object.is equality
 ✓  chromium  src/without-mock.test.ts (1 test) 0ms

 FAIL   chromium  src/with-mock.test.ts > randomString
AssertionError: expected '43587017925835303' to be '__MOCK__' // Object.is equality

System Info

System:
    OS: macOS 15.5
    CPU: (8) arm64 Apple M2
    Memory: 66.75 MB / 24.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.19.3 - /opt/homebrew/opt/node@20/bin/node
    Yarn: 1.22.22 - /opt/homebrew/bin/yarn
    npm: 10.8.2 - /opt/homebrew/opt/node@20/bin/npm
    pnpm: 10.11.0 - /opt/homebrew/bin/pnpm
    bun: 1.2.15 - /opt/homebrew/bin/bun
  Browsers:
    Chrome: 137.0.7151.122
    Safari: 18.5
    Safari Technology Preview: 26.0
  npmPackages:
    @vitest/browser: ^3.2.4 => 3.2.4
    playwright: ^1.53.2 => 1.53.2
    vite: ^7.0.0 => 7.0.0
    vitest: ^3.2.4 => 3.2.4

Used Package Manager

npm

Validations

Sub-issues

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationfeat: browserIssues and PRs related to the browser runner

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions