vitest-dev / vitest-dev/vitest

Add `vi.createMockFromModule` (Like `jest.createMockFromModule`)

Open
#5,482 15 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

discussion feat: module mocking
Dominant language
TypeScript
Stars
17.1k
Forks
2k
Avg merge
1d 22h
Merged PRs (30d)
94

Description

Clear and concise description of the problem

I want to create a manual mock (__mocks__), but only specialize parts of the default mock that is automatically created by vitest, in Jest I could do:

import { jest } from '@jest/globals';

const mod = jest.createMockFromModule<typeof import('../foo')>('../foo');
mod.bar = jest.fn(() => 'qux');
export = mod;

But createMockFromModule is not available in Vitest, and importMock is not the same, as when used inside a manual mock, it just ends up importing the manual mock itself cyclicly. createMockFromModule always returns the automatically created mock object even if there is a manual mock.

Suggested solution

Add vi.createMockFromModule or under a different name that better fits it's async nature in vitest, that acts like vi.importMock but always return an automatically created mock even if there is a manual mock.

Alternative

Manually mock everything in the manual mock, which is cumbersome and harder to maintain.

Additional context

Encountered while migrating some tests from Jest to Vitest due to Jest's ESM issues.

https://github.com/vitest-dev/vitest/discussions/3718

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 by reading the existing vi.importMock behavior and the manual-mock flow described in this issue, including how mocks is resolved. Define the new API's async behavior and verify that it returns the automatically generated mock rather than the manual mock, including the partial-specialization use case shown above.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
testing
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.