酶和反应路由器:如何使用useHistory浅化呈现组件

时间:2020-01-01 14:08:11

标签: reactjs react-router react-hooks enzyme

我一直在尝试使用shallow提供的enzyme渲染组件。

该组件正在使用useHistory中的react-router-dom

const baseMatch: match<{ id: string }> = { /* path, url, params */};
const location = createLocation(baseMatch.url);

describe('MyComponent', () => {
  const baseProps = {
    history: createMemoryHistory(),
    location: createLocation(baseMatch.url),
    match: baseMatch
  };

  beforeEach(() => {
    jest.mock('react-router-dom', () => ({
      useHistory: jest.fn()
    }));
  });

  afterEach(() => { jest.clearAllMocks() });

  it('renders blah blah', () => {
    const wrapper = shallow(<MyComponent {...baseProps} />);
    // testing MyComponent here...
  });

我提到了this post,并以同样的方式放入jest.mock

但是,结果为TypeError: Cannot read property 'history' of undefined

控制台说:

MyComponent › renders blah blah

    TypeError: Cannot read property 'history' of undefined

      24 | const MyComponent = (props: IProps) => {
      25 |   console.log('useHistory', useHistory);
    > 26 |   let history = useHistory();

奇怪的是,上面第25行中的console.log打印了useHistory的实现(换句话说,它不是未定义的)。

很显然,useHistory没有被嘲笑。 我怀疑useHistory不能被shallow嘲笑(在上面的帖子中,发布者正在使用mount())。

但是,我不确定100%,因为我无法从shallowuseHistory的文档中找到enzyme是否与react-router兼容。

是否可以将shallowuseHistory一起使用?任何建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

来自docs

注意:为了正确模拟,Jest需要jest.mock('moduleName') 与require / import语句的作用域相同。

因此,不要在beforeEach中模拟react-router-dom,而是尝试将其放在顶级范围内:

jest.mock('react-router-dom', () => ({
  useHistory: jest.fn()
}));

const baseMatch: match<{ id: string }> = { /* path, url, params */};
const location = createLocation(baseMatch.url);


describe('MyComponent', () => {
  const baseProps = {
    history: createMemoryHistory(),
    location: createLocation(baseMatch.url),
    match: baseMatch
  };

...