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.
In today’s fast-paced work environment, meetings are essential but can often feel unproductive. However, by…
Gold is one of the most coveted precious metals in the world, adored for its…
Gold, the shimmering metal synonymous with wealth, power, and beauty, has been deeply intertwined with…
How to Onboard an Intern in a Small, Individual-Based Company Hiring an intern can be…