如何在玩笑中模拟 useHistory 钩子?

Iva*_*yuk 48 typescript reactjs jestjs react-router enzyme

我在带有打字稿的 react router v5.1.2 中使用 UseHistory 钩子吗?运行单元测试时,我遇到了问题。

类型错误:无法读取未定义的属性“历史”。

import { mount } from 'enzyme';
import React from 'react';
import {Action} from 'history';
import * as router from 'react-router';
import { QuestionContainer } from './QuestionsContainer';

describe('My questions container', () => {
    beforeEach(() => {
        const historyHistory= {
            replace: jest.fn(),
            length: 0,
            location: { 
                pathname: '',
                search: '',
                state: '',
                hash: ''
            },
            action: 'REPLACE' as Action,
            push: jest.fn(),
            go: jest.fn(),
            goBack: jest.fn(),
            goForward: jest.fn(),
            block: jest.fn(),
            listen: jest.fn(),
            createHref: jest.fn()
        };//fake object 
        jest.spyOn(router, 'useHistory').mockImplementation(() =>historyHistory);// try to mock hook
    });

    test('should match with snapshot', () => {
        const tree = mount(<QuestionContainer />);

        expect(tree).toMatchSnapshot();
    });
});
Run Code Online (Sandbox Code Playgroud)

我也试过使用,jest.mock('react-router', () =>({ useHistory: jest.fn() }));但它仍然不起作用。

Pro*_*bat 60

在浅化使用useHistory.

在我的测试文件中使用以下模拟解决了:

jest.mock('react-router-dom', () => ({
  useHistory: () => ({
    push: jest.fn(),
  }),
}));
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法捕获 `useHistory().push()` 调用? (8认同)
  • 但是如何监视 useHistory 函数呢? (4认同)
  • 对于使用 TypeScript 的用户来说,如果组件同时使用“Link”和“useHistory”,这种方法可能会导致“React.createElement:类型无效 - 需要一个字符串”错误。Erhan的方法不会导致这个问题。 (2认同)

Erh*_*han 41

这个对我有用:

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useHistory: () => ({
    push: jest.fn()
  })
}));
Run Code Online (Sandbox Code Playgroud)

  • @Erhan 我也做了同样的事情。但它再次抛出错误:TypeError:无法读取未定义的属性“历史记录”。有什么建议吗? (6认同)

Ale*_*x W 24

这是一个更详细的例子,取自工作测试代码(因为我很难实现上面的代码):

组件.js

  import { useHistory } from 'react-router-dom';
  ...

  const Component = () => {
      ...
      const history = useHistory();
      ...
      return (
          <>
              <a className="selector" onClick={() => history.push('/whatever')}>Click me</a>
              ...
          </>
      )
  });
Run Code Online (Sandbox Code Playgroud)

组件.test.js

  import { Router } from 'react-router-dom';
  import { act } from '@testing-library/react-hooks';
  import { mount } from 'enzyme';
  import Component from './Component';
  it('...', () => {
    const historyMock = { push: jest.fn(), location: {}, listen: jest.fn() };
    ...
    const wrapper = mount(
      <Router history={historyMock}>
        <Component isLoading={false} />
      </Router>,
    ).find('.selector').at(1);

    const { onClick } = wrapper.props();
    act(() => {
      onClick();
    });

    expect(historyMock.push.mock.calls[0][0]).toEqual('/whatever');
  });
Run Code Online (Sandbox Code Playgroud)


tar*_*mon 15

戴着我的政治帽子,我敢说你问错了问题。

不是useHistory你想嘲笑。相反,您只想为它提供您控制的历史对象。

这也允许您检查push调用,就像 2 个最重要的答案一样(在撰写本文时)。

如果确实如此,createMemoryHistory请支持您:

import {Router} from 'react-router-dom'
import {createMemoryHistory} from 'history'

test('QuestionContainer should handle navigation', () => {
  const history = createMemoryHistory()
  const pushSpy = jest.spyOn(history, 'push') // or 'replace', 'goBack', etc.
  render(
      <Router history={history}>
        <QuestionContainer/>
      </Router>
  )
  userEvent.click(screen.getByRole('button')) // or whatever action relevant to your UI
  expect(pushSpy).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)


Iva*_*yuk 13

在 github react-router repo 中,我发现 useHistory 钩子使用单例上下文,当我开始在挂载 MemoryRouter 中使用时,它找到了上下文并开始工作。所以修复它

import { MemoryRouter } from 'react-router-dom';
const tree =  mount(<MemoryRouter><QuestionContainer {...props} /> </MemoryRouter>);
Run Code Online (Sandbox Code Playgroud)


小智 7

模拟useHistory的push功能的一种方法:

import reactRouterDom from 'react-router-dom';
jest.mock('react-router-dom');

const pushMock = jest.fn();
reactRouterDom.useHistory = jest.fn().mockReturnValue({push: pushMock});
Run Code Online (Sandbox Code Playgroud)

然后,如何检查该函数是否被调用:

expect(pushMock).toHaveBeenCalledTimes(1);
expect(pushMock).toHaveBeenCalledWith('something');
Run Code Online (Sandbox Code Playgroud)