To write unit tests in React, we can use the react-dom/test-utils
package.
For instance, we write
import React from "react";
export default function Hello(props) {
if (props.name) {
return <h1>Hello, {props.name}!</h1>;
} else {
return <span>Hey, stranger</span>;
}
}
in hello.js
.
Then in hello.test.js, we write
import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import Hello from "./hello";
let container = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
// cleanup on exiting
unmountComponentAtNode(container);
container.remove();
container = null;
});
it("renders with or without a name", () => {
act(() => {
render(<Hello />, container);
});
expect(container.textContent).toBe("Hey, stranger");
act(() => {
render(<Hello name="Jenny" />, container);
});
expect(container.textContent).toBe("Hello, Jenny!");
act(() => {
render(<Hello name="Margaret" />, container);
});
expect(container.textContent).toBe("Hello, Margaret!");
});
to add a test for the Hello
component.
We mount the component with render
Then we check the rendered content with expect
.
The beforeEach
callback runs before each test.
We use
container = document.createElement("div");
to create the render target element.
And the afterEach
callback runs after each test.
We clean up after our tests in the afterEach
callback.