Testing in React

Today we were practicing running tests on our React apps using Jest. To mimic the browser APIs that interact with the DOM Jest comes with jsdom set-up, which we use React Testing Library (RTL) to render our React components to.

We can import methods from RTL to render, access and fire events to the jsdom.

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import ToggleButton from "/filename";

test("The button changes text when clicked", () => {
  render(<ToggleButton>click me</ToggleButton>);
  // renders the React component
  const buttonNode = screen.getByText("click me");
  // finds an element with the specified text content
  // triggers the click event
  screen.getByText("just clicked");
  // checks if the same element now has the updated text content