vitest-dev / vitest-dev/vitest

Cannot dynamic import multiple times a mocked module

Open
#7,040 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

p3-minor-bug
Dominant language
TypeScript
Stars
17.1k
Forks
2k
Avg merge
1d 22h
Merged PRs (30d)
94

Description

Describe the bug

When dynamically importing several times the same mocked module, we may fail to import it on subsequent imports.

Reproduction

The reproduction will be clearer than the description above:

// src/main.js
const load = () => import("./constants");
export async function preload() {
  load();
}
export async function compute() {
  return (await load()).default;
}
// test/main.spec.js
import { test, vi ,expect} from "vitest";
import { preload, compute } from "../src/main";

vi.mock("../src/constants.js", () => ({ default: "from-mock" }));

test("sum", async () => {
  preload();
  expect(await compute()).toBe("from-mock"); // failing, we receive the unmocked value, if we drop preload it works
  // if we change compute to do: return { first: (await load()).default, second: (await load()).default };
  // we receive the unmocked and the mocked value
});

Reproduction at: https://github.com/dubzzz/imported-twice-vitest-bug

System Info
System:
    OS: Linux 6.5 Ubuntu 20.04.6 LTS (Focal Fossa)
    CPU: (2) x64 Intel(R) Xeon(R) Platinum 8370C CPU @ 2.80GHz
    Memory: 5.50 GB / 7.74 GB
    Container: Yes
    Shell: 5.0.17 - /bin/bash
  Binaries:
    Node: 20.17.0 - ~/nvm/current/bin/node
    Yarn: 1.22.22 - /usr/bin/yarn
    npm: 10.8.2 - ~/nvm/current/bin/npm
    pnpm: 9.11.0 - ~/nvm/current/bin/pnpm
  npmPackages:
    vitest: ^2.1.8 => 2.1.8
Used Package Manager

npm

Validations

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproduction in src/main.js and test/main.spec.js, using the linked imported-twice-vitest-bug project and its npm setup. Confirm the differing results between preload followed by compute and repeated load calls, then trace Vitest's dynamic-import mocking path. Done means repeated imports consistently return the mocked value and the regression is covered by a test.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, node.js, typescript
Domain
testing-qa
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.