0

这是我的自定义钩子: 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

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

4

1 回答 1

0

您需要与renderHook结合使用act。像这样的东西:

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-12-03T14:14:00.613 回答