vitest-dev / vitest-dev/vitest
Add `vi.createMockFromModule` (Like `jest.createMockFromModule`)
Nobody has claimed this yet.
- 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
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
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 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