Skip to content

Commit

Permalink
handle undefined returns of module mocks, and update migration docs
Browse files Browse the repository at this point in the history
  • Loading branch information
jereklas committed Aug 10, 2022
1 parent bee20f6 commit 1f72543
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
13 changes: 13 additions & 0 deletions docs/guide/migration.md
Original file line number Diff line number Diff line change
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, if the factory argument returned a primitive, the mock would implicitly mock the default export. In Vitest, the factory argument has to return an object where each export is explicitly defined. For example, the following `jest.mock` would have to be updated as follows:

```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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit 1f72543

Please sign in to comment.