Skip to content

Mocks are lost when reruning the tests in browser mode when using MSW #6633

@foxaltus

Description

@foxaltus

Describe the bug

Whenever you mock a module in browser mode and rerun the tests, mocks are non longer effective (the original module is used instead).

EDIT: this issue only occurrs when the MSW worker is active... so I'm not sure if it's a bug or if there is an explanation for the behaviour.

Reproduction

  1. Configure Vitest with browser mode (playwright + chromium)
  2. Add msw as dependency and initialize the worker script with pnpm exec init public --save
  3. In vitest-setup.ts, start the worker with beforeAll(async () => await worker.start());
  4. Create a mock-me.ts file with export default "original"; for instance
  5. In vitest-setup.ts, mock the module with vi.mock("./mock-me", () => ({ default: "mocked" }));
  6. Import and log the variable in the tested component
  7. Run vitest
  8. console prints "mocked"
  9. Rerun the test by pressing r or a in the terminal
  10. console prints "original"

Repo: https://github.com/foxaltus/vitest-browser-mode-repro

System Info

System:
    OS: Windows 11 10.0.22631
    CPU: (8) x64 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
    Memory: 6.77 GB / 31.73 GB
  Binaries:
    Node: 18.20.2 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 10.5.0 - C:\Program Files\nodejs\npm.CMD
    pnpm: 9.9.0 - ~\AppData\Local\pnpm\pnpm.EXE
  Browsers:
    Edge: Chromium (127.0.2651.105)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    @vitejs/plugin-react: ^4.3.1 => 4.3.1
    @vitest/browser: ^2.1.1 => 2.1.1
    @vitest/coverage-v8: ^2.1.1 => 2.1.1
    vite: ^5.4.8 => 5.4.8
    vitest: ^2.1.1 => 2.1.1

Used Package Manager

pnpm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    feat: browserIssues and PRs related to the browser runnerp3-minor-bugAn edge case that only affects very specific usage (priority)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions