// SearchForm.jsx import { useState } from "react"; export default function SearchForm({ onSubmit }) { const [value, setValue] = useState(""); function handleSubmit(e) { e.preventDefault(); onSubmit(value); } return (
setValue(e.target.value)} />
); } // SearchForm.test.jsx import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { test, expect, vi } from "vitest"; import SearchForm from "./SearchForm"; test("calls onSubmit with the typed value", async () => { const user = userEvent.setup(); const handleSubmit = vi.fn(); render(); await user.type(screen.getByRole("textbox"), "react"); await user.click(screen.getByRole("button", { name: "Search" })); expect(handleSubmit).toHaveBeenCalledWith("react"); }); /* Notes: - vi.fn() creates a fake function with no real implementation — the test only cares whether it was called, and with what argument. - getByRole("textbox") finds the input by its implicit accessible role, without needing a test-specific id or class name on it. - toHaveBeenCalledWith("react") confirms the exact value SearchForm passed to onSubmit matches what was actually typed. */