// Counter.jsx
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
return (
Count: {count}
);
}
// Counter.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { test, expect } from "vitest";
import Counter from "./Counter";
test("increments the count each time +1 is clicked", async () => {
const user = userEvent.setup();
render();
expect(screen.getByText("Count: 0")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "+1" }));
expect(screen.getByText("Count: 1")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "+1" }));
expect(screen.getByText("Count: 2")).toBeInTheDocument();
});
/*
Notes:
- The test never reaches into Counter's internal count state
directly — it only checks the rendered text, exactly the
"test what the user sees" philosophy from the chapter.
- Each await user.click() simulates one real click and waits for
React to finish re-rendering before the next assertion runs.
*/