Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle undefined returns of module mocks, and update migration docs (#1763) #1830

Merged
merged 2 commits into from Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/guide/migration.md
Expand Up @@ -14,6 +14,19 @@ Jest has their [globals API](https://jestjs.io/docs/api) enabled by default. Vit

If you decide to keep globals disabled, be aware that common libraries like [`testing-library`](https://testing-library.com/) will not run auto DOM [cleanup](https://testing-library.com/docs/svelte-testing-library/api/#cleanup).

**Module mocks**

When mocking a module in Jest, the factory argument's return value is the default export. In Vitest, the factory argument has to return an object with each export explicitly defined. For example, the following `jest.mock` would have to be updated as follows:
sheremet-va marked this conversation as resolved.
Show resolved Hide resolved

```diff
- jest.mock('./some-path', () => 'hello')
+ vi.mock('./some-path', () => ({
+ default: 'hello',
+ })
```

For more details please refer to the [vi.mock api](/api/#vi-mock)

**Auto-Mocking Behaviour**

Unlike Jest, mocked modules in `<root>/__mocks__` are not loaded unless `vi.mock()` is called. If you need them to be mocked in every test, like in Jest, you can mock them inside [`setupFiles`](/config/#setupfiles).
Expand Down
2 changes: 2 additions & 0 deletions examples/mocks/test/factory.test.ts
Expand Up @@ -7,6 +7,7 @@ vi
.mock('../src/example', () => ({
mocked: true,
then: 'a then export',
ok: undefined,
square: (a: any, b: any) => a + b,
asyncSquare: async (a: any, b: any) => Promise.resolve(a + b),
}))
Expand Down Expand Up @@ -60,6 +61,7 @@ describe('mocking with factory', () => {
})

test('defined exports on mock', async () => {
expect((example as any).ok).toBe(undefined)
expect((example as any).then).toBe('a then export')
expect((example as any).mocked).toBe(true)
expect(example.square(2, 3)).toBe(5)
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/runtime/mocker.ts
Expand Up @@ -122,7 +122,7 @@ export class VitestMocker {
if (target instanceof Promise)
return target.then.bind(target)
}
else if (val === undefined) {
else if (!(prop in target)) {
throw new Error(`[vitest] No "${prop}" export is defined on the "${dep}"`)
}

Expand Down