full example look useTodo.test.ts
-
to mock module you can use
vi.mock('path/to/module', factory)
wherefactory
is a function that return all exported member from the module. if you dont provide the factory module, all exported member from the module willundefined
. also you can use global mock module using__mocks__
folder in the root folder or alongside the modulevi.mock('@/modules/axios', () => { return { http: { get: vi.fn().mockResolvedValue({ data: true }) } } })
-
use
vi.mocked
to get the exported mock function from the module that have been mocked. test the exported mocked member usingvi.isMockFunction(fn)
expect(vi.isMockFunction(AxiosModule.http.get)).toBe(true)
-
you can then override the mock function return value, or implementation
vi.mocked(AxiosModule.http.get).mockImplementationOnce(() => { return Promise.resolve({ data: mockAll }) })
full example look useManage.spec.ts
After you mock the module, you can use fn().mockReset()
to reset the inner implementation to undefined
. If you intent to change the implementation you can use this and apply new implementation
- mock module using
vi.mock('path/to/module')
then add the exported member
vi.mock('@/libs/useLib', () => ({
useLib: vi.fn(() => ({
plus: vi.fn(),
minus: vi.fn(),
clear: vi.fn()
}))
}))
- reset the mocked module using
.mockReset()
const mocked = vi.mocked(useLib, { partial: true }).mockReset()
- define exported member from the mocked module, since it will return undefined
const spy = vi.fn()
mocked.mockImplementationOnce(() => ({
clear: vi.fn(),
minus: spy.mockReturnValueOnce('mocked'),
plus: vi.fn()
}))