vitest-dev / vitest

Next generation testing framework powered by Vite.
https://vitest.dev
MIT License
13.13k stars 1.18k forks source link

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

Open segevfiner opened 7 months ago

segevfiner commented 7 months ago

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

hi-ogawa commented 7 months ago

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.

Is this maybe a bug? Or if it's causing some infinite loop, that needs to be fixed at least?

segevfiner commented 7 months ago

Not an infinite loop, you are just getting your own module namespace object as far as I can tell. And I think importMock is supposed to import manual mocks so not a bug as far as I can tell.

hi-ogawa commented 7 months ago

And I think importMock is supposed to import manual mocks so not a bug as far as I can tell.

It's called importMock, which sounds like an opposite of importActual https://vitest.dev/api/vi.html#vi-importactual but I thought the intent is simply "import actual + auto mocking" and could behave like Jest's createMockFromModule https://jestjs.io/docs/jest-object#jestcreatemockfrommodulemodulename.

https://github.com/vitest-dev/vitest/blob/e4e939ba2ab48c67ee14b82ec957fc9a8a52756c/packages/vitest/src/runtime/mocker.ts#L437-L455

Btw, can you setup a small reproduction to illustrate what you want to do with a concrete code? That would be helpful anyway as a test case if it's implemented. Also it would also help for us to suggest a workaround with what's currently possible.

One idea just came to my mind is to still use vi.mock and overwrite some exports like this:

// use `setupFiles` to setup mock for all test files

import { vi, beforeEach } from "vitest"
import * as fooLib from "./foo";

// setup auto mocking for a whole module
vi.mock("./foo");

beforeEach(() => {
  // then customize some named export
  vi.mocked(fooLib).bar.mockImplementation(() => 'qux');
});
segevfiner commented 5 months ago

@hi-ogawa Here is an attempt to show what I'm trying to do, though a bit of a contrived example, I hope it shows what I'm trying to do: https://github.com/segevfiner/vitest-partial-manual-mock

sheremet-va commented 5 months ago

I don't think we can support any dynamic imports for this use case because ESM needs to know every named import during parsing, but maybe we can support something like this:

// __mocks__/foo.js

export * from '../foo.js' with { mock: 'auto' }
export const bar = vi.fn(() => 'qux')
segevfiner commented 5 months ago

I don't think we can support any dynamic imports for this use case because ESM needs to know every named import during parsing, but maybe we can support something like this:

// __mocks__/foo.js

export * from '../foo.js' with { mock: 'auto' }
export const bar = vi.fn(() => 'qux')

AFAIK you can do dynamic imports in ESM, aka import(), though it is async so you will need top level await, what's not supported is dynamic export, e.g. replace the entire exports of this module with the given object, which is why I had to use export = which kinda fakes it by transpiling to CJS (module.exports = ...), but a valid way of doing this without relying on some special handling of that syntax by Vitest might be needed as you suggested.

sheremet-va commented 5 months ago

AFAIK you can do dynamic imports in ESM, aka import(), though it is async so you will need top level await, what's not supported is dynamic export

Yes, this is what I meant. The JS engine cannot parse the file to see all exported variables if you use a dynamic import because there is no mechanism to dynamically export variables.

e.g. replace the entire exports of this module with the given object, which is why I had to use export = which kinda fakes it by transpiling to CJS (module.exports = ...), but a valid way of doing this without relying on some special handling of that syntax by Vitest might be needed as you suggested.

This only works in Node.js runner because Vitest supports loading source code as CJS, this will not work in the browser (and module mocking is supported in the browser mode in the latest beta). This will also not work in future versions of Vitest because we cannot process files that were imported using require (you can currently import this file, but you cannot import other things in this file without leaving Vitest module system because all imports are transformed into require if it uses the CJS transform).

on some special handling of that syntax by Vitest might be needed as you suggested.

Also, export = is not an ESM syntax and it requires special handling to process already. My proposal already works with the ESM syntax, and it only requires the processing of the foo file, not the __mocks__/foo file.

rezam7596 commented 3 weeks ago

To achieve the desired behavior, I used vi.mock within the __mocks__ file:

// __mocks__/foo.js

vi.mock('../foo.js', async (importOriginal) => ({
  ...(await importOriginal()),
  bar: vi.fn(() => 'qux')
}));

In the test file, I included:

vi.mock('./foo.js');

Initially, I wasn’t certain this logic would work, given that vi.mock is running within the __mocks__ directory. While it achieves the same behavior as jest.createMockFromModule, this approach may be impacted by future updates in Vitest, so it’s something to monitor.

segevfiner commented 3 weeks ago

Last time I tried, I got an infinite loop from vi.mock as it imported back the same manual mock module I'm currently defining.

rezam7596 commented 2 weeks ago

For me, with the latest version (2.1.4), it worked