Skip to content

vi.mock() does not replace the modules implementation in browser mode #9706

@bimbiltu

Description

@bimbiltu

Describe the bug

vi.mock('some-module') calls do not replace the modules implementation when running in browser mode. Instead, they appear to behave as if vi.mock('some-module', {spy: true}) was used and wrap the original implementation in spys.

As a workaround, you can setup empty mocks using a factory function or by importing the mocked functions and giving them a new mockImplementation

Reproduction

https://github.com/bimbiltu/vitest-browser-mock-repro

This repo has 3 simple files:

// src/answer.ts
export const answer = () => 42;
// src/getTheAnswer.ts
import { answer } from './answer';
export const getTheAnswer = () => answer();
import { it, expect, vi } from 'vitest';
import { getTheAnswer } from './getTheAnswer';
import { answer } from './answer';

vi.mock('./answer')

// fails but should pass
it('should not return 42 when the answer module is mocked', () => {
  expect(getTheAnswer()).not.toBe(42);
});

it('should replace answer with a mock', () => {
  getTheAnswer();
  expect(answer).toHaveBeenCalled();
});

System Info

System:
    OS: macOS 26.3
    CPU: (10) arm64 Apple M1 Pro
    Memory: 1.58 GB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 24.13.1 - /Users/USER/.asdf/installs/nodejs/24.13.1/bin/node
    Yarn: 1.22.22 - /Users/USER/.asdf/installs/nodejs/24.13.1/bin/yarn
    npm: 11.8.0 - /Users/USER/.asdf/plugins/nodejs/shims/npm
    pnpm: 8.9.2 - /opt/homebrew/bin/pnpm
    Watchman: 2025.08.04.00 - /opt/homebrew/bin/watchman
  Browsers:
    Chrome: 145.0.7632.77
    Firefox: 140.7.0
    Safari: 26.3
  npmPackages:
    @vitest/browser-playwright: ^4.0.18 => 4.0.18
    vitest: ^4.0.18 => 4.0.18

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions