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.
Break! I didn’t plan it. One day I just didn’t feel like opening Instagram—and then…
AI tools Let’s be real—AI sounds like either a robot apocalypse or something only tech…
Summer vacation is a great time for kids to explore, have fun, and learn new…
Goal: Understand transformers, large language models, and the architecture behind ChatGPT. Tutorial Suggestions: ✅ “Transformers…
Goal: Build apps or tools with ChatGPT or GPT-4 API. Tutorial Suggestions: ✅ OpenAI API…
Goal: Learn how to prompt better, write content, brainstorm, code, etc. Tutorial Suggestions: ✅ OpenAI's…