我正在尝试测试一个自定义挂钩 useCopySystem,它在内部使用另一个自定义挂钩 useBackdrop。我想在执行期间模拟useBackdrop在pasteCopiedDay中的行为,以防止它失败。 useBackdrop 钩子取决于用户是否在线,但我只想直接将其值设置为 true,以便在测试期间返回特定值。
const createTestStore = () =>
configureStore({
reducer: {
auth: authReducer,
global: globalReducer,
misc: miscReducer,
},
});
const testStore = createTestStore();
// Wrapper
const wrapper = ({ children }: { children: ReactNode }) => <Provider store={testStore}>{children}</Provider>;
describe('test copy system', () => {
// Render the pasteCopiedDay hook
const {
result: {
current: { pasteCopiedDay },
},
} = renderHook(() => useCopySystem(), { wrapper });
// Mock the internal custom hook (must return true in order to the fn to continue
// This mock is not affecting pasteCopiedDay
jest.mock('../utilities/useBackdrop', () => ({
__esModule: true,
useBackdrop: jest.fn(() => ({
showBackdrop: jest.fn(() => true),
})),
}));
it('pasteCopiedDay', async () => {
await pasteCopiedDay('day3Id', mockedCopyDayType);
})
在导入useCopySystem之前模拟useBackdrop,以便在导入useCopySystem时,它使用useBackdrop的模拟版本。
beforeEach(() => {
jest.resetAllMocks();
});
// Mock useBackdrop before importing useCopySystem
jest.mock('../utilities/useBackdrop', () => ({
__esModule: true,
useBackdrop: jest.fn(() => ({
showBackdrop: jest.fn(() => true),
})),
}));
// Wrapper
const createTestStore = () =>
configureStore({
reducer: {
auth: authReducer,
global: globalReducer,
misc: miscReducer,
},
});
const testStore = createTestStore();
const wrapper = ({ children }: { children: ReactNode }) => <Provider store={testStore}>{children}</Provider>;
describe('test copy system', () => {
// Render the pasteCopiedDay hook
const {
result: {
current: { pasteCopiedDay },
},
} = renderHook(() => useCopySystem(), { wrapper });
it('pasteCopiedDay', async () => {
await pasteCopiedDay('day3Id', mockedCopyDayType);
});
});