Skip to content

Browser mode: vi.mock in a setup file doesn't work for static imports #11519

Description

@kasperpeulen

Describe the bug

I mock a module in my setup file:

// setup.ts
import { vi } from "vitest";

vi.mock("./weather.ts", () => ({ getWeather: () => "sunny" }));

And use it in a test:

// static.test.ts
import { expect, test } from "vitest";
import { getWeather } from "./weather.ts";

test("gets the mock from the setup file", () => {
  expect(getWeather()).toBe("sunny");
});

In browser mode this fails. The test gets the real module:

AssertionError: expected 'rain' to be 'sunny'

It does work if I use await import("./weather.ts") in the test, or if I add a vi.mock to the test file itself.

It worked in 4.1.11 and 5.0.0-beta.6. It fails every time in 5.0.0 and 5.0.3.

It looks like the test file is imported before the mock from the setup file is ready. #11450 reported the same thing, but the author closed it and it isn't fixed.

I have a small fix with a test and will open a PR.

The text is in my own words. Opus 5.5 found the fix, made the reproduction and posted this for me, reviewed by Fable 5.1.

Reproduction

https://github.com/kasperpeulen/vitest-setup-mock-repro

pnpm install && pnpm exec playwright install chromium && pnpm test

System Info

  System:
    OS: macOS 26.5.1
    CPU: (10) arm64 Apple M1 Pro
  Binaries:
    Node: 24.18.0
    pnpm: 11.28.2
  Browsers:
    Chrome: 155.0.8059.39
  npmPackages:
    @vitest/browser-playwright: 5.0.3 => 5.0.3
    vitest: 5.0.3 => 5.0.3

Used Package Manager

pnpm

Validations

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions