【发布时间】:2021-01-21 03:36:18
【问题描述】:
我正在尝试使用 @testing-library/react-hooks 测试自定义挂钩,但我无法测试依赖项。我们以useEffect 为例:
import { renderHook } from '@testing-library/react-hooks';
import { useEffect } from 'react';
test('test dependency', () => {
const callback = jest.fn((value: number) => {});
let currentValue = 5;
renderHook(() => useEffect(() => callback(currentValue), [currentValue]));
expect(callback).toBeCalledTimes(1);
expect(callback).toHaveBeenLastCalledWith(5);
renderHook(() => useEffect(() => callback(currentValue), [currentValue]));
expect(callback).toBeCalledTimes(1); // error here: called 2 times in reality
expect(callback).toHaveBeenLastCalledWith(5);
currentValue = 6;
renderHook(() => useEffect(() => callback(currentValue), [currentValue]));
expect(callback).toBeCalledTimes(2);
expect(callback).toHaveBeenLastCalledWith(6);
});
预期行为:useEffect 未使用相同的依赖项列表再次调用。
实际行为:useEffect 每次都被调用,可能是因为上下文被销毁并在 renderHook 之间重新创建。
我也尝试将渲染方法放入一个常量中,如下所示:
const myHook = () => useEffect(() => callback(currentValue), [currentValue]);
renderHook(myHook);
但没有运气。有什么方法可以测试依赖列表是否正常工作?
【问题讨论】:
标签: reactjs unit-testing jestjs react-hooks