Reactive states
Handling component state changes.
reactive-component.js
import Button from "./button";
const ReactiveComponent = () => {
const [name, setName] = useState(null)
useEffect(() => {
setTimeout(() => {
setName("Klipfolio")
}, 1000)
},[])
return (<div>
<h1>{name ? `Welcome to ${name}` : "Loading"}</h1>
</div>)
}
reactive-component.test.js
import React from "react";
import {render, screen} from "test-utils";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";
import ReactiveComponent from './reactive-component'
describe("reactive-component", () => {
test("should render button", () => {
render(<ReactiveComponent/>);
const heading = screen.getByRole("heading", {level: 1})
expect(heading).toHaveTextContent("Loading");
waitFor(() => {
exepct(heading).toHaveTextConent("Welcome to Klipfolio");
})
})
})
At render, there are no state changes, jest holds off all setState calls. When querying the screen for the heading, we should expect it to have
"Loading"` as its content.We know there is a state change, therefore we call the
waitForfunction which tells jest we are expecting a state change and to wait for it to happen.Telling jest we expect the heading to have the new text content of
"Welcome to Klipfolio"it will advance the state calls, and if the new content is correct, the test passes, otherwise will fail.