如何使用 Enzyme 为 React Router 创建 URL 参数的单元测试

问题描述 投票:0回答:1

我正在尝试使用 React Router 的 Enzyme 来测试 url 参数。到目前为止,该应用程序很简单。我有 App.jsx,它有一个

<Router />
组件、一个
<Switch />
组件和两个
<Route />
组件。

在设置测试以将 URL 作为

path
中的
<Route />
并返回子
<Files />
组件中路径存根的值时,我们将不胜感激。

我对测试完全陌生,所以请链接文档(如果有的话),并请伪代码或演示您的方法的概述,以便我可以将其放入正确的上下文中。

我还没有看到任何适合我的理解水平的足够的或上下文化的方法来测试 URL 参数功能。这里有一个答案建议使用 Jest 进行模拟,如何使用新的 React 路由器钩子测试组件?但是没有足够的上下文供我实现。

这是 create-react-app 的基本站立:

function App() {
  const [user] = useState(sampleUser);

  return (
    <UserContext.Provider value={user}>
      <SiteHeader />
      <Router>
        <Switch>
          <Route path="/files/:fileId">
            <Files />
          </Route>
          <Route path="*">
            <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <p>
                Edit
                <code>src/App.js</code>
                and save to reload.
              </p>
              <a
                className="App-link"
                href="https://reactjs.org"
                target="_blank"
                rel="noopener noreferrer"
              >
                Learn React
              </a>
            </header>
          </Route>
        </Switch>
      </Router>
    </UserContext.Provider>
  );
}

export default App;

我有兴趣单独测试

<Files />
,并传递 URL。
<Files />
fileId
钩子上解构
useParams

文件组件如下所示:

import React from 'react';
// import PropTypes from 'prop-types';
import { useParams, Router } from 'react-router-dom';

const Files = () => {
  const { fileId } = useParams();
  return (
    <main>
      {`component for ${fileId}`}
    </main>
  );
};

Files.propTypes = {};

Files.defaultProps = {};

export default Files;

对于我的测试,我导入文件和路由,因为文件使用

path
钩子继承了路由的
useParams
。我正在安装
<Route path="/files/:fileId" component={Files} />
,并用
<MemoryRouter initialEntries={['/files/mockId']} initialIndex={0}>
包裹它以获取状态。完整的代码如下所示:

import React from 'react';
import { mount, shallow, configure, render } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { MemoryRouter, matchPath, useParams } from 'react-router-dom';
import Files from './Files.jsx';
import Route from '../../App.jsx';

configure({ adapter: new Adapter() });

describe('FilesPage', () => {

  it('has fileId of `mockId`', () => {
    const wrapper = mount(
      <MemoryRouter initialEntries={['/page-tagger/mockId']} initialIndex={0}>
        <Route path="/page-tagger/:fileId" component={Files} />
        // <Files />
      </MemoryRouter>
    );

    // Get value fileId from <Files />
  });
});

我尝试了许多不同的方法来从

<Files />
组件中获取任何值,但无济于事。我尝试过
shallow(<Files />)
,但这会导致
useParams
在 Files.jsx 文档中未定义的错误。所以,我安装并使用了
<MemoryRouter />
。当我看到wrapper.props()的样子时,我可以看到
<Route />
有props()。App的children元素有路径,并且钩子
useParam
不是
<Files />的道具或任何东西
<MemoryRouter />
中的 url 不会传递给子级
<Route />
也不会传递给
<Files />

reactjs unit-testing react-router jestjs enzyme
1个回答
0
投票

React Router 基于一个名为

history
的包,它处理与浏览器的所有交互。

您可以创建一个 Router 并向其传递历史记录实例以在测试期间管理 URL :

import {createMemoryHistory} from 'history';

test('', () => {
  const history = createMemoryHistory();
  mount(
    <Router history={history}>
      /* your components */
    </Router>
  )
})
© www.soinside.com 2019 - 2024. All rights reserved.