【问题标题】:How to use testing library jest-dom with the new version React V6?如何在新版本的 React V6 中使用测试库 jest-dom?
【发布时间】:2021-12-05 13:43:31
【问题描述】:

我正在开发我的 React 应用程序,当我尝试使用 React 测试库进行一些单元测试时。我无法成功运行测试。

有谁知道这是否与 V6 React 升级有关?

这是我尝试运行的示例测试代码:

import { render, screen } from '@testing-library/react';
import App from './App';

test('renders a button to enter', () => {
  render(<App />);
  const linkElement = screen.getByText(/Play/i);
  expect(linkElement).toBeInTheDocument();
});

App.js

function App() {
  return (
    <div className="App">
      <Routes>
        <Route exact path="/" element={<LandingPage />} />
        <Route exact path="/home" element={<Home />} />
        <Route exact path="/videogame/:id" element={<Detail />} />
        <Route exact path="/creategame" element={<CreateGame />} />
      </Routes>
    </div>
  );
}

export default App;

登陆页面

const LandingPage = () => {
  return (
    <div className="landing">
      <Link to="/home">
        <button className="landingBtn">Play</button>
      </Link>
    </div>
  );
};

export default LandingPage;

谢谢!

【问题讨论】:

  • “我无法成功运行我的测试” - 你能说得更具体些吗?什么没有按预期工作?另外,请提供被测组件的代码。
  • 错误是:Test Suites: 0 of 1 total ● 呈现按钮进入 useRoutes() 只能在 组件的上下文中使用。

标签: reactjs react-testing-library


【解决方案1】:

由于您正在测试 App 组件并且它包含路由,因此您不能在此处选择 /Play/i 文本元素,而是导入要测试的确切组件。

react-testing-library with react router

用于测试路由器文件

将路由器模拟为 div 并包含其子代码。这通过以下方式工作: 您需要包含以下代码的文件夹__mocks__/react-router-dom.js

import React from 'react';

const reactRouterDom = require("react-router-dom")
reactRouterDom.BrowserRouter = ({children}) => <div>{children}</div>
module.exports = reactRouterDom

现在您可以使用 MemoryRouter 来定义 Route 应该指向的路径。

App.test.js:

import React from "react";
import { render } from "@testing-library/react";
import { MemoryRouter } from 'react-router-dom';
import App from './App';

describe("unit-test", () => {
    it("renders the right component with following path '/home'", () => {
        const { getByTestId } = render(
            <MemoryRouter initialEntries={['/home']}>
                <App></App>
            </MemoryRouter>
        )

        let HomeComponent= getByTestId("home-component")

        expect(HomeComponent).toBeInTheDocument()
    })
})

【讨论】:

    猜你喜欢
    • 2020-12-15
    • 1970-01-01
    • 2021-06-14
    • 2022-06-11
    • 2019-04-22
    • 2021-06-04
    • 2021-11-30
    • 2020-03-24
    • 1970-01-01
    相关资源
    最近更新 更多