feat: vi.mock can be used inside setupFiles to automock libraries

This commit is contained in:
Vladimir Sheremet 2022-01-17 14:58:58 +03:00
parent ca9507d9d0
commit dda62d0af8
4 changed files with 15 additions and 7 deletions

View File

@ -1086,16 +1086,16 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo
### vi.mock
**Type**: `(path: string, factory?: () => any) => void`
**Type**: `(path: string, factory?: () => unknown) => void`
Makes all `imports` to passed module to be mocked. Inside a path you _can_ use configured Vite aliases.
- If there is a `factory`, will return its result. The call to `vi.mock` is hoisted to the top of the file,
so you don't have access to variables declared in the global file scope, if you didn't put them before imports!
- If `__mocks__` folder with file of the same name exist, all imports will return its exports.
- If there is no `__mocks__` folder or a file with the same name inside, will call original module and mock it.
- If `factory` is defined, will return its result. Factory function can be asynchronous. You may call [`vi.importActual`](#vi-importactual) inside to get the original module. The call to `vi.mock` is hoisted to the top of the file, so you don't have access to variables declared in the global file scope!
- If `__mocks__` folder with file of the same name exist, all imports will return its exports. For example, `vi.mock('axios')` with `<root>/__mocks__/axios.ts` folder will return everything exported from `axios.ts`.
- If there is no `__mocks__` folder or a file with the same name inside, will call original module and mock it. (For the rules applied, see [algorithm](/guide/mocking#automocking-algorithm).)
Additionally, 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).
Additionally, unlike Jest, mocked modules in `__mocks__` are not loaded unless `vi.mock()` is called.
### vi.mockCurrentDate
- **Type**: `(date: string | number | Date) => void`

View File

@ -0,0 +1 @@
export const mocked = false

View File

@ -4,6 +4,7 @@ import { value as virtualValue } from 'virtual-module'
import { two } from '../src/submodule'
import * as mocked from '../src/mockedA'
import { mockedB } from '../src/mockedB'
import * as globalMock from '../src/global-mock'
vitest.mock('../src/submodule')
vitest.mock('virtual-module', () => {
@ -14,6 +15,10 @@ test('submodule is mocked to return "two" as 3', () => {
assert.equal(3, two)
})
test('globally mocked files are mocked', () => {
expect(globalMock.mocked).toBe(true)
})
test('can mock esm', () => {
const spy = vi.spyOn(mocked, 'mockedA')

View File

@ -1,4 +1,6 @@
import { beforeEach } from 'vitest'
import { beforeEach, vi } from 'vitest'
vi.mock('../src/global-mock', () => ({ mocked: true }))
beforeEach(() => {
// console.log(`hi ${s.name}`)