首页 > 解决方案 > 使用 withRouter 时代码覆盖率返回 0%

问题描述

快速总结 - 我有一个 React 应用程序。单元测试库是反应测试库。该组件包含在 react-router-dom 的 withRouter 中

问题 - 代码覆盖率显示为 0%,即使它显示 8 个测试通过并且一些信息被跳过。如果我从 withRouter 中取出组件,代码覆盖率会显示正确的覆盖率结果。

请检查下面我尝试匹配快照的代码。

// Profile.test.js
import React from "react";
import Profile from "./Profile";
import { withRouter } from "react-router-dom";
import { render } from "react-testing-library";

it("renders the component", async () => {
  const container = withRouter(<Profile />);
  expect(container).toMatchSnapshot();
});

// Profile.js
import react from 'react';
import { withRouter } from "react-router-dom";

const Profile = () => {
    return (
        <div>The profile component</div>
    )
}

export default withRouter(Profile);

我应该能够将 withRouter 用于组件并查看覆盖范围。

标签: reactjsroutesreact-routerreact-router-domreact-testing-library

解决方案


我认为你的测试应该是这样的:

it('renders the component', () => {
  const component = mount(<BrowserRouter><Profile /></BrowserRouter>);
  expect(component).toMatchSnapshot();
});

推荐阅读