vitest-dev / vitest-dev/vitest
Cannot dynamic import multiple times a mocked module
Nobody has claimed this yet.
- 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
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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