Categories
Learning Tech

How to write basic Test case for React component using Jest or Enzyme

Lets quickly straight dive into it

import React from "react";
import { shallow } from "enzyme";
import TestComponent from "./TestComponent";

describe("TestComponent", () => {
  it("renders correctly", () => {
    const wrapper = shallow(<TestComponent />);
    expect(wrapper).toMatchSnapshot();
  });

  it("contains a button", () => {
    const wrapper = shallow(<TestComponent />);
    expect(wrapper.find("button").length).toEqual(1);
  });

  it("simulates click events", () => {
    const mockCallBack = jest.fn();
    const wrapper = shallow(<TestComponent handleClick={mockCallBack} />);
    wrapper.find("button").simulate("click");
    expect(mockCallBack.mock.calls.length).toEqual(1);
  });
});

In this example, the describe block creates a test suite for the TestComponent and the it blocks define individual test cases.

The shallow function from Enzyme is used to render a shallow version of the component.

The toMatchSnapshot assertion is used to check that the component is rendering correctly.

The find method is used to locate elements within the shallow render, and the simulate method is used to trigger events on those elements.

The jest.fn function is used to create a mock callback that can be passed as a prop to the component and tested.

Happy Learning.