首页 > 解决方案 > 在 useEffect 挂钩内测试路由器

问题描述

我有以下组件。
希望测试push内部的路由器方法useEffect是否正在使用特定路径和搜索进行调用。

import React from 'react';
import { compose } from 'redux';
import { withRouter } from 'react-router';

const MyComponent = ({
  router: { push, location },
}) => {
    const version = 'v2';
  React.useEffect(() => {
    push({
      pathname: `/${version}/new_path`,
      search: location.search ? location.search: '',
    });
  }, []);
  return <div>Sample div text</div>
};

const higherOrder = compose(
  withRouter,
  aCustomHigherOrderC,
);

export default higherOrder(MyComponent);

这是我编写的测试,用于测试router是否正确调用。

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from '../src/components/MyComponent';

jest.spyOn(React, 'useEffect').mockImplementation(f => f());

const props = {
  router: {
    push: jest.fn(),
    location: {
      search: '?param=1',
    },
  },
};

describe('MyComponent component tests', () => {
  it('should work', () => {
    const render = () => shallow(
      <MyComponent {...props} />
    );
    expect(props.router.push).toHaveBeenCalledWith('/v2/new_path?param=1');
  });
});

但是当我运行测试时出现以下错误。

错误:expect(jest.fn()).toHaveBeenCalledWith(expected)

预期的模拟函数已被调用:["/v2/new_path?param=1"] 但它没有被调用。

好像我什至没有进入useEffect。确实尝试在那里添加一个断点,但我没有达到那个断点。我能否就我做错了什么以及如何测试使用正确路径和搜索参数调用它的路由器获得一些建议?谢谢。

标签: javascriptreactjsjestjsreact-routerenzyme

解决方案


推荐阅读