【问题标题】:How to spyOn to react custom hook returned value?如何 spyOn 对自定义钩子返回值做出反应?
【发布时间】:2021-03-15 12:50:23
【问题描述】:

这是我的自定义钩子: useCustomModal.ts

export const useCustomModal = (modalType: string) => {
  const setModal = () => {
    // ... functionality here
  };

  const handleModalClose = (modalType: string) => {
    // ... functionality here
    setModal();
    // ...
  };

  return {
    handleModalClose,
    setModal,
  };
};

这是我的测试: useCustomModal.ts

import { act } from '@testing-library/react-hooks';

import { useCustomModal } from './useCustomModal';

describe('some', () => {
  it('a test', async () => {
    await act(async () => {
      const actions = useCustomModal('test');
      const spy = jest.spyOn(actions, 'setModal');
      actions.handleModalClose('test');
      expect(spy).toBeCalledTimes(1);
    });
  });
});


测试失败: 预计通话次数:1 接听电话数:0

如何正确监视自定义反应钩子?

【问题讨论】:

    标签: reactjs typescript jestjs react-hooks react-hooks-testing-library


    【解决方案1】:

    您需要将renderHookact 结合使用。像这样的:

    import { renderHook, act } from '@testing-library/react-hooks';
    
    import { useCustomModal } from './useCustomModal';
    
    describe('some', () => {
      it('a test', () => {
        const { result } = renderHook(() => useCustomModal('test'));
        const spy = jest.spyOn(result.current, 'setModal');
        act(() => {
          result.current.handleModalClose('test');
        });
        expect(spy).toBeCalledTimes(1);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 1970-01-01
      • 2020-05-18
      • 2020-08-20
      • 2021-01-26
      • 2020-03-08
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      相关资源
      最近更新 更多