与路由器一起使用时,代码覆盖率返回 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);

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

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

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

旨在用于在应用程序中注入路由器数据。

在测试中,您必须将路由器呈现为组件树的一部分:

import { MemoryRouter } from 'react-router-dom';
it('renders the component', () => {
const { container } = render(<MemoryRouter><Profile /></MemoryRouter>);
expect(container).toMatchSnapshot();
});

我建议您不要仅使用快照测试,以确保您的应用程序正常工作。

最新更新