大家好,我是 jest 的新手,现在正在为我们的 customHooks 进行一些测试。
我的 customHook 里面有 useEffect 并且不返回值:
const useCustomHook = (func: EffectCallback, deps?: DependencyList) => {
const didMount = useRef(false);
useEffect(() => {
if (didMount.current) func();
else didMount.current = true;
}, deps);
};
我想做的是在组件挂载后不会调用回调函数,而是在依赖项更新后调用。
我当前的 test.ts 正在使用 jest 和 @testing-library/react-hooks 并且是这样的:
describe('Testing if useCustomHook works as expected', () => {
test('Check if only fire after dep updates', async () => {
const callBackMock = jest.fn();
let dependencyList = [{ dep: 'dep' }];
const { result,} = renderHook(() =>
useCustomHook(callBackMock, dependencyList)
);
expect(callBackMock).toHaveBeenCalledTimes(0);
expect(result.current).toBeUndefined();
act(() => {
dependencyList[0].dep = 'foo';
});
expect(callBackMock).toHaveBeenCalledTimes(1);
});
});
更新dependencyList 后,不会再次触发效果。@testing-library/react-hooks 确实提供了一个名为 waitForNextUpdate 的方法,但使用它时出现超时错误。由于我的钩子不返回值,result.current 也是未定义的。
那么,如何测试我的钩子是否按预期工作?谢谢你。