To write a Jest test in a React app, you will need to import the component that you want to test and the expect function from Jest. You can then write a test that renders the component using ReactDOM.render or mount from enzyme, interacts with the component using wrapper.find and wrapper.simulate, and makes an assertion using the expect function.
Here is an example of a test that checks if a button element in a component is disabled when the isDisabled prop is true:
import MyButton from "./MyButton";
import { mount } from "enzyme";
import React from "react";
test("MyButton is disabled when isDisabled prop is true", () => {
const wrapper = mount(<MyButton isDisabled={true} />);
const button = wrapper.find("button");
expect(button.props().disabled).toBe(true);
});
You can then run your tests using the jest command.
Here are a few more tips for writing Jest tests for React components:
Use describe blocks to organize your tests and make your test output easier to read. You can nest describe blocks to create a hierarchy of tests.
Use beforeEach and afterEach blocks to set up and tear down common resources that are needed by multiple tests. This can help make your tests more efficient and reduce duplication.
Consider using enzyme to mount and interact with your components. enzyme provides a number of useful methods for finding elements within a wrapper and simulating events, which can make your tests more concise.
Use snapshot tests to verify that the structure and content of your components have not changed unexpectedly. Snapshot tests can be especially useful for testing components that are generated by templates or contain a lot of dynamic content.
Remember to test for both expected and unexpected behavior. This includes testing edge cases and handling errors gracefully.
import MyForm from "./MyForm";
import { mount } from "enzyme";
import React from "react";
test("MyForm sets error message when invalid email is entered", () => {
const wrapper = mount(<MyForm />);
const input = wrapper.find('input[type="email"]');
input.simulate("change", { target: { value: "invalid" } });
const error = wrapper.find(".error");
expect(error.text()).toBe("Please enter a valid email address");
});
In this test, we use enzyme to mount the MyForm component, find the email input field, and simulate a change event. We then find the element with the error class and make an assertion about its text content.