Home > database >  Should you test that all components render without crashing?
Should you test that all components render without crashing?

Time:11-15

I am completely new to testing react applications. I am wondering is there a need for testing that every component renders without crashing, or does just testing the App component suffice as it is the parent of all components?

Also, any tip and what to test for in a component would be great :)

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 />);
  });
});

For example, in another component would I do the following test:

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/>);
  });
});

CodePudding user response:

I recommend react-test-renderer for this purpose:

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();
    });
});

Now, regarding the approach to testing: it's a whole philosophy, different people have different points of view, but the common standard is to maximize the test coverage via running jest --coverage in command line. My approach is to test the vital functionalities of an app.

CodePudding user response:

Following react-testing-library guiding principles, it is best to only test specific components rather than the entire App as it states you want to avoid testing child components. So to answer your question, using this library you want to test each component individually as it's made for unit testing.

If you wanted to test your entire application in a single test, you would be looking for end-to-end test frameworks, such as Cypress.

  • Related