如何使用 Jest 使用新的 React Router Hooks 模拟 history.push [英] How to mock history.push with the new React Router Hooks using Jest

查看:57
本文介绍了如何使用 Jest 使用新的 React Router Hooks 模拟 history.push的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 react-router 上的新 useHistory 钩子中模拟 history.push 并使用 @testing-library/反应.我只是像这里的第一个答案一样嘲笑模块:How to test组件使用新的反应路由器钩子?

所以我在做:

//NotFound.jsimport * as React from 'react';从'react-router-dom'导入{useHistory};const RouteNotFound = () =>{const 历史 = useHistory();返回 (<div><button onClick={() =>history.push('/help')}/>

);};导出默认 RouteNotFound;

//NotFound.test.js描述('RouteNotFound',()=> {it('点击时重定向到正确的 URL', () => {const mockHistoryPush = jest.fn();jest.mock('react-router-dom', () => ({...jest.requireActual('react-router-dom'),useHistory: () =>({推:模拟历史推,}),}));const { getByRole } = 渲染(<MemoryRouter><RouteNotFound/></MemoryRouter>);fireEvent.click(getByRole('button'));期望(mockHistoryPush).toHaveBeenCalledWith('/help');});})

但是 mockHistoryPush 没有被调用...我做错了什么?

解决方案

你实际上不需要模拟 react-router-dom(至少对于 v5),因为它提供了一堆测试工具: https://v5.reactrouter.com/web/guides/testing

要检查您的历史记录是否实际更改,您可以使用 createMemoryHistory 并检查其内容:

从'react'导入React;从'@testing-library/react'导入{渲染,屏幕};从@testing-library/user-event"导入 userEvent;从'./Menu'导入{菜单};从历史"导入 { createMemoryHistory }从'react-router-dom'导入{路由器};test('触发路径改变', () => {const 历史 = createMemoryHistory();使成为(<路由器历史={历史}><菜单/></路由器>);const aboutItem = screen.getByText('About');期望(aboutItem).toBeInTheDocument();userEvent.click(aboutItem);期望(历史.长度).toBe(2);期望(history.location.pathname).toBe('/about');});

I am trying to mock history.push inside the new useHistory hook on react-router and using @testing-library/react. I just mocked the module like the first answer here: How to test components using new react router hooks?

So I am doing:

//NotFound.js
import * as React from 'react';
import { useHistory } from 'react-router-dom';


const RouteNotFound = () => {
  const history = useHistory();
  return (
    <div>
      <button onClick={() => history.push('/help')} />
    </div>
  );
};

export default RouteNotFound;

//NotFound.test.js
describe('RouteNotFound', () => {
  it('Redirects to correct URL on click', () => {
    const mockHistoryPush = jest.fn();

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

    const { getByRole } = render(
        <MemoryRouter>
          <RouteNotFound />
        </MemoryRouter>
    );

    fireEvent.click(getByRole('button'));
    expect(mockHistoryPush).toHaveBeenCalledWith('/help');
  });
})

But mockHistoryPush is not called... What am I doing wrong?

解决方案

You actually do not need to mock react-router-dom (at least for v5) as it provides a bunch of testing tools: https://v5.reactrouter.com/web/guides/testing

To check your history is actually changed, you can use createMemoryHistory and inspect its content:

import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Menu } from './Menu';
import { createMemoryHistory } from 'history'
import { Router } from 'react-router-dom';

test('triggers path change', () => {
  const history = createMemoryHistory();

  render(
    <Router history={history}>
      <Menu />
    </Router>
  );

  const aboutItem = screen.getByText('About');
  expect(aboutItem).toBeInTheDocument();

  userEvent.click(aboutItem);
  expect(history.length).toBe(2);
  expect(history.location.pathname).toBe('/about');
});

这篇关于如何使用 Jest 使用新的 React Router Hooks 模拟 history.push的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆