React useEffect hook开玩笑的单元测试未确认调用了函数prop

时间:2020-09-21 03:56:46

标签: reactjs unit-testing jestjs react-hooks enzyme

我正在尝试编写一个单元测试,以检查useEffect挂钩中是否有另一个支持为真的函数(作为支持传递)。单元测试无法确认在useEffect挂钩中调用了(模拟的)函数,但可以确认调用了来自导入模块的spyOn的函数。有谁知道可能是什么问题?谢谢!

import {getUser} from './Auth';
export function ComponentA({
  shouldRetryExport,
  someReduxDispatchFunc,
}) {

  const handleExport = useCallback(async () => {
    const user = await getUser();
    someReduxDispatchFunc();
  }, []);

  useEffect(() => {
    if (shouldRetryExport) {
      handleExport();
    }
  }, [shouldRetryExport]);

  return (<SomeComponent />)
});

单元测试:

import * as Auth from './Auth';

it('should call someReduxDispatchFunc if getUserAuthorization is true', () => {
  const getAuthUserSpy = jest.spyOn(Auth, 'getUser');
  const someReduxDispatchFuncMock = jest.fn();
  const props = {
    someReduxDispatchFunc: someReduxDispatchFuncMock,
    shouldRetryExportWithUserReAuthorization: true,
  };
  enzyme.mount(<ComponentA {...props} />);

  expect(getAuthUserSpy).toHaveBeenCalled(); // works -> returns true
  expect(someReduxDispatchFuncMock).toHaveBeenCalled(); // doesn't work -> returns false
});

似乎与useEffect的useCallback有关。如果我删除useCallback并在其中添加逻辑到useEffect,它可以捕获someReduxDispatchFuncMock被调用。

1 个答案:

答案 0 :(得分:0)

我认为问题不是来自useCallbackuseEffect。问题很可能是您的回调函数采用了异步功能,这意味着它需要时间来解决。

为此,您必须以异步方式进行测试,然后等待其得到解决,如下所示:

it('should call someReduxDispatchFunc if getUserAuthorization is true', async () => {
  const getAuthUserSpy = jest.spyOn(Auth, 'getUser');
  const someReduxDispatchFuncMock = jest.fn();
  const props = {
    someReduxDispatchFunc: someReduxDispatchFuncMock,
    shouldRetryExport: true,
  };
  enzyme.mount(<ComponentA {...props} />);

  // wait for getting resolved
  await Promise.resolve();

  expect(getAuthUserSpy).toHaveBeenCalled();
  expect(someReduxDispatchFuncMock).toHaveBeenCalled();
});