我有一个名为 useInitialSetup
的自定义钩子,它返回一个键值字典对象。
它正在 App.tsx 中使用。
在 App.test.tsx 中,我有一套使用 Jest 和 React 测试库编写的单元测试。
是否可以仅在部分单元测试中模拟 useInitialSetup
,而不是全部?
这是我在 App.test.tsx 中尝试过的:
jest.mock('../../hooks/useInitialSetup', () => {
return jest.fn(() => ({
loading: mockLoading,
suspendedTrial: mockSuspendedTrial,
maxTrials: mockMaxTrials,
reachedMaxTrials: mockReachedMaxTrials,
}));
});
it('Unit test that uses a mocked version of useInitialSetup', () => {
render(<App/>)
...
})
it('Unit test that uses the real implementation of useInitialSetup', () => {
jest.dontMock('../../hooks/useInitialSetup')
render(<App/>)
...
})
单元测试 #2 仍然使用 useInitialSetup
的模拟版本。
答案 0 :(得分:0)
这就是我最终做的事情。这让我可以为这个选定的单元测试模拟我的 useInitialSetup
自定义钩子的输出。任何后续单元测试都将使用此钩子的默认实现。
import * as useInitialSetup from '../../hooks/useInitialSetup';
it('Test', () => {
const spy = jest.spyOn(useInitialSetup, 'default');
spy.mockReturnValue({
loading: false,
reachedMaxTrials: true,
errorCheckingCanCreateInstance: false,
errorFetchingUser: false,
// @ts-ignore
suspendedTrial: mockSuspendedTrial,
resetChecks: () => {},
maxTrials: 1,
});
render(setupComponent());
expect(true).toBe(true) // or whatever assertion you want
spy.mockRestore();
})