【问题标题】:React useEffect hook jest unit test doesn't confirm function prop is calledReact useEffect hook jest 单元测试未确认调用了函数 prop
【发布时间】:2021-01-07 04:17:49
【问题描述】:

我正在尝试编写一个单元测试来检查一个函数(作为一个 prop 传递)是否在 useEffect 钩子中另一个 prop 为 true 时被调用。单元测试无法确认在 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
});

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

【问题讨论】:

  • someReduxDispatchFuncSpy 更改为 someReduxDispatchFuncMock
  • 对不起@slideshowp2 - 它实际上已经是 someReduxDispatchFuncMock 了。我在提供的示例中有错字。谢谢!

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


【解决方案1】:

我认为问题不是来自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();
});

【讨论】:

  • 耶@tmhao2005!我还意识到我必须使用const getAuthUserSpy = jest.spyOn(Auth, 'getUser').mockImplementation(() =&gt; Promise.resolve(...)); 而不是...mockResolvedValue(),因为后者不起作用!谢谢你的指点!
猜你喜欢
  • 2021-11-27
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 2021-08-08
  • 2021-10-08
相关资源
最近更新 更多