RTL:仅为选定的单元测试模拟自定义 React 挂钩
RTL: Mock a custom React hook only for selected unit tests
我有一个名为 useInitialSetup
的自定义挂钩,它 returns 是一个键值字典对象。
它在 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
的模拟版本。
这是我最后做的。这让我可以为这个选定的单元测试模拟 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();
})
我有一个名为 useInitialSetup
的自定义挂钩,它 returns 是一个键值字典对象。
它在 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
的模拟版本。
这是我最后做的。这让我可以为这个选定的单元测试模拟 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();
})