User Events
Test components by interacting with your component just like a user would.
import React from "react";
import {render, screen} from "test-utils";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";
import ComponentWithButton from "./component";
describe("ComponentWithButton", await () => {
test("can click button and creates h1 tag", () => {
render(<ComponentWithButton />);
userEvent.click(screen.getByRole("button"));
const heading = await screen.findByRole("heading", {level: 1})
expect(heading).toBeInTheDocument();
})
})
When calling a userEvent we have to use the asynchronous calls from RTL to tell it that we are expecting the dom to change.
findByRole is an async call that will try and find the new element and throw an error if it couldn't find it.
if we wanted to expect that an element is no longer in the dom, we would use queryByRole instead and expect it not.toBeInTheDocument()