Skip to content

module mock does not work in some cases in browser mode #6034

@kwojcik

Description

@kwojcik

Describe the bug

When mocking the contentful package in browser mode, the mock doesn't seem to apply the first time tests are run and the mocked named export is undefined. Rerunning the tests causes the named export to be a spy, but it does not register being called.

Changing to the jsdom environment causes tests to pass.

import { createClient as contentfulCreateClient } from "contentful";
import { createClient as localCreateClient } from "../src/contentful.js";
import { vi, expect, describe, it } from "vitest";

const mocks = vi.hoisted(() => ({
  contentfulMock: vi.fn(),
  localMock: vi.fn(),
}));
vi.mock("contentful", () => ({
  createClient: mocks.contentfulMock,
}));
vi.mock("../src/contentful.js", () => ({
  createClient: mocks.localMock,
}));

describe("mocking", () => {
  describe("from contentful", () => {
    it("can make a client", () => {
      // this fails, it's undefined?
      contentfulCreateClient({
        accessToken: "accessToken",
        space: "space",
      });
      expect(mocks.contentfulMock).toHaveBeenCalled();
    });
  });
  describe("from local", () => {
    it("can make a client", () => {
      localCreateClient({
        accessToken: "accessToken",
        space: "space",
      });
      expect(mocks.localMock).toHaveBeenCalled();
    });
  });
});

First test run: TypeError: createClient is not a function
2nd test run: AssertionError: expected "spy" to be called at least once

Reproduction

https://github.com/kwojcik/vitestsourcemapbug/tree/contentfulMock

git checkout contentfulMock
npm install
npm test

Rerunning the tests gives a different error

System Info

System:
    OS: macOS 13.6.7
    CPU: (12) arm64 Apple M2 Max
    Memory: 6.03 GB / 64.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.18.2 - ~/.asdf/installs/nodejs/18.18.2/bin/node
    Yarn: 1.22.21 - /opt/homebrew/bin/yarn
    npm: 9.8.1 - ~/.asdf/plugins/nodejs/shims/npm
    pnpm: 9.4.0 - /opt/homebrew/bin/pnpm
    Watchman: 2024.04.01.00 - /opt/homebrew/bin/watchman
  Browsers:
    Chrome: 126.0.6478.127
    Safari: 16.6
  npmPackages:
    @vitest/browser: v2.0.0-beta.12 => 2.0.0-beta.12
    @vitest/ui: latest => 2.0.0-beta.12
    vite: latest => 5.3.2
    vitest: v2.0.0-beta.12 => 2.0.0-beta.12

Used Package Manager

npm

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