【问题标题】:Should you test that all components render without crashing?您是否应该测试所有组件在没有崩溃的情况下呈现?
【发布时间】:2021-11-13 18:30:39
【问题描述】:

我对测试反应应用程序完全陌生。我想知道是否需要测试每个组件在不崩溃的情况下呈现,还是只测试 App 组件就足够了,因为它是所有组件的父级?

此外,任何提示以及在组件中测试的内容都会很棒:)

import { render } from "@testing-library/react";
import App from "./App";

// Test that the App Component renders without crashing
describe("App", () => {
  test("renders App component", () => {
    render(<App />);
  });
});

例如,在另一个组件中,我会做以下测试:

import { render } from "@testing-library/react";
import App from "./App";

// Test that the AnotherComp Component renders without crashing
describe("AnotherComp", () => {
  test("renders App component", () => {
    render(<AnotherComp/>);
  });
});

【问题讨论】:

    标签: reactjs testing react-testing-library


    【解决方案1】:

    为此我推荐react-test-renderer

    import App from './App';
    import renderer from 'react-test-renderer';
    
    
    describe("App rendering specification", () => {
        it('App is rendered', () => {
            const component = renderer.create(
                <App/>
            );
            const tree = component.toJSON();
            expect(tree).toMatchSnapshot();
        });
    });
    

    现在,关于测试方法:这是一个完整的哲学,不同的人有不同的观点,但共同的标准是通过在命令行中运行jest --coverage 来最大化测试覆盖率。我的方法是测试应用的重要功能。

    【讨论】:

    • 谢谢。所以这个测试渲染了整个应用程序,所以不需要将它添加到每个组件中?
    • 而且,每个组件都应该有一个特定的测试吗?还是仅仅取决于组件的功能?
    • 不,快照只是“冻结”了组件当时的样子,我的意思是它呈现的 html。您应该单独测试每个组件的快照,并手动测试其中的所有功能。
    【解决方案2】:

    按照react-testing-library 指导原则,最好只测试特定组件而不是整个应用程序,因为它声明you want to avoid testing child components. 所以要回答你的问题,使用这个库你想单独测试每个组件,因为它是为单元制作的测试。

    如果您想在单个测试中测试整个应用程序,您会寻找端到端测试框架,例如 Cypress.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2016-03-19
      • 2015-12-08
      • 1970-01-01
      • 2014-05-29
      相关资源
      最近更新 更多