测试反应自定义钩子(反应测试库)

时间:2021-01-20 15:38:36

标签: reactjs jestjs react-testing-library

我需要找到一种方法来测试这个自定义钩子。

  1. 确保使用 element.addEventListenertransitionend 调用 callback
  2. 模拟 transitionend 事件,并确保调用 element.removeEventListeneranimationendcallback
const useAnimation = ({ draggable, ifWaiting }) => {
   const [ifAnimationAlive, setAnimation] = useState(true);

   const element = draggable.current && draggable.current.resizableElement && draggable.current.resizableElement.current;

   const callback = useCallback(() => {
      setAnimation(false);
      element.removeEventListener('animationend', callback);
   }, [element]);

   useEffect(() => {
      if (element && ifWaiting && ifAnimationAlive) {
         element.addEventListener('transitionend', callback);
      }
   }, [element, ifWaiting, ifAnimationAlive, callback]);

   return ifAnimationAlive;
};

我已经找到了很多关于 addEventListener 的例子。但它们都不适合我,因为他们使用 document 对其进行了测试,而我希望它与特定元素一起使用。

到目前为止,我已经设法制作了这样的东西:

 test('should call addEventListener', () => {
      const ifWaiting = true;
      const draggable = {
         current: {
            resizableElement: {
               current: {
                  addEventListener: jest.fn()
               }
            }
         }
      }

      renderHook(() => useAnimation, { initialProps: { draggable, ifWaiting }});

      expect(draggable.current.resizableElement.current.addEventListener).toBeCalled()
   })

我模拟了 addEventListenerdraggable 元素,将 ifWaiting 作为 true 传递,以便可以调用 addEventListener

但是测试说这个函数没有被调用。

1 个答案:

答案 0 :(得分:0)

renderHook 在您的测试中使用不正确,这意味着从未调用过钩子。

要么直接在回调函数中调用带有参数的钩子:

renderHook(() => useAnimation({ draggable, ifWaiting }));

或者使用钩子作为回调并在选项中传递它的道具:

renderHook(useAnimation, { initialProps: { draggable, ifWaiting } });