Unit testing

One of the most important concepts in React or any other project is testing. There are 3 levels of testing: Unit testing, Integration testing, and then End-to-End testing.

  • Unit testing is a type of testing where we test only a single component in isolation. There are a lot of frameworks that can be used to do unit testing like: Jest, Mocha, Chai, etc. It is useful to write test cases that cover both ideal and edge cases. Writing tests while developing components allows you to test components as and when you create them. This methodology is known as Test Drive Development.
  • Basic code for a test case:
import { render, screen } from "@testing-library/react";
import Register from "./Register";

describe("Register component", () => {
  it("should render Register component correctly", () => {
    render(<Register />);
    const element = screen.getByRole("heading");
    expect(element).toBeInTheDocument();
  });
});
  • Describe is used to group test cases logically.
  • The It block makes up for the actual test case. The render function renders the component for testing.
  • expect function takes an argument that is checked against a matching function.
  • Here’s a list of all the matches.
  • There can be a lot of test cases in a single describe block. If you have any network calls, intervals, or functions dependent on timers or some OS-level functions make sure to mock them by writing manual mocks since test cases need to be tested with custom data.
  • Check this official documentation regarding manual mocking.