I have the following files in a React app with Vitest (which has the same API as Jest):
// hooks/useEntities/useEntities.ts
return useEntities() {
// this hooks send api requests so I will mock it in the test file.
}
// SomeComponent.tsx
import useEntities from 'hooks/useEntities/useEntities'
function SomeComponent () {
const entities = useEntities()
return <div>...</div>
}
// SomeComponent.test.tsx
vi.mock('hooks/useEntities/useEntities', () => ({ // this mocking seems to work
default: [...]
}))
describe(...) {
it(...) {
render(<SomeComponent />)
}
}
Because I mock a lot of hooks this way. I want to separate the mocking part to a different file, so it can be reused. I've tried to following ways without a success:
// init.ts
vi.mock('hooks/useEntities/useEntities', () => ({
default: [...]
}))
// SomeComponent.test.tsx => this mocking seems to work
await init()
describe(...) {
it(...) {
render(<SomeComponent />)
}
}
also tried this way:
// init.ts
vi.mock('hooks/useEntities/useEntities', () => ({
default: [...]
}))
// SomeComponent.test.tsx => this mocking seems to work
describe(...) {
beforeAll(async () => {
await init()
await init(vi) // tried the same thing with passing the vi instance to the init function in the separate file
})
it(...) {
render(<SomeComponent />)
}
}
__mocks__
folder? - jestjs.io/docs/manual-mocks - vitest.dev/guide/mocking.html#automocking-algorithm – Percent