Skip to content

Commit

Permalink
fix: handle undefined returns of module mocks, and update migration d…
Browse files Browse the repository at this point in the history
…ocs (#1763) (#1830)

* handle undefined returns of module mocks, and update migration docs

* correct docs
  • Loading branch information
jereklas committed Aug 11, 2022
1 parent 39b19cf commit 8eddd5a
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
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:

```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

0 comments on commit 8eddd5a

Please sign in to comment.