Mat*_*kin 6 javascript jestjs react-testing-library vite vitest
我在带有 Vitest 的 React 应用程序中有以下文件(它具有与 Jest 相同的 API):
// hooks/useEntities/useEntities.ts
return useEntities() {
// this hooks send api requests so I will mock it in the test file.
}
Run Code Online (Sandbox Code Playgroud)
// SomeComponent.tsx
import useEntities from 'hooks/useEntities/useEntities'
function SomeComponent () {
const entities = useEntities()
return <div>...</div>
}
Run Code Online (Sandbox Code Playgroud)
// SomeComponent.test.tsx
vi.mock('hooks/useEntities/useEntities', () => ({ // this mocking seems to work
default: [...]
}))
describe(...) {
it(...) {
render(<SomeComponent />)
}
}
Run Code Online (Sandbox Code Playgroud)
因为我用这种方式模拟了很多钩子。我想将模拟部分分离到不同的文件中,以便可以重复使用。我尝试过以下方法但没有成功:
// init.ts
vi.mock('hooks/useEntities/useEntities', () => ({
default: [...]
}))
Run Code Online (Sandbox Code Playgroud)
// SomeComponent.test.tsx => this mocking seems to work
await init()
describe(...) {
it(...) {
render(<SomeComponent />)
}
}
Run Code Online (Sandbox Code Playgroud)
也尝试过这种方式:
// init.ts
vi.mock('hooks/useEntities/useEntities', () => ({
default: [...]
}))
Run Code Online (Sandbox Code Playgroud)
// 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 />)
}
}
Run Code Online (Sandbox Code Playgroud)