Leaf and Kettle's tea list, /teas, reads its search from the URL: /teas?q=mint lists the mint teas, so a search can be shared, bookmarked, and reloaded. The page is a Server Component that reads searchParams. Build the search box it shows: app/teas/search-box.tsx, whose default export is SearchBox.
It's a Client Component, since it reacts to typing, so the file starts with "use client". Show an input labelled Search teas, which starts with the q that's in the URL.
As the visitor types, change the URL with router.replace, so every key doesn't add a history entry, and with { scroll: false }, so the page doesn't jump to the top. Keep the URL's other search params, like sort, but remove page, because a new search starts on its first page. When the box is empty, remove q too.
/teas?sort=price&page=3, then you type m
→ router.replace("/teas?sort=price&q=m", { scroll: false })
renderClient(<SearchBox />, { url: "/teas?q=mint" });
expect(screen.getByLabelText("Search teas")).toHaveValue("mint");
renderClient(<SearchBox />, { url: "/teas" });
await user.type(screen.getByLabelText("Search teas"), "oolong");
expect(router.url).toBe("/teas?q=oolong");
expect(router.history).toEqual(["/teas?q=oolong"]);
expect(router.calls.length).toBe(6);
expect(router.calls.every((call) => call.method === "replace")).toBe(true);
renderClient(<SearchBox />, { url: "/teas?sort=price&page=3" });
await user.type(screen.getByLabelText("Search teas"), "m");
expect(router.url).toBe("/teas?sort=price&q=m");
renderClient(<SearchBox />, { url: "/teas?q=mint&sort=name" });
await user.clear(screen.getByLabelText("Search teas"));
expect(router.url).toBe("/teas?sort=name");
cleanup();
renderClient(<SearchBox />, { url: "/teas?q=mint" });
await user.clear(screen.getByLabelText("Search teas"));
expect(router.url).toBe("/teas");
renderClient(<SearchBox />, { url: "/teas" });
await user.type(screen.getByLabelText("Search teas"), "g");
expect(router.calls).toEqual([{ method: "replace", href: "/teas?q=g", options: { scroll: false } }]);
async function TeasPage({ searchParams }) {
const { q } = await searchParams;
return (
<main>
<h1>Teas{q ? " matching " + q : ""}</h1>
<SearchBox />
</main>
);
}
await renderServer(<TeasPage searchParams={params({ q: "green" })} />, { url: "/teas?q=green" });
expect(screen.getByRole("heading", { name: "Teas matching green" })).toBeInTheDocument();
expect(screen.getByLabelText("Search teas")).toHaveValue("green");
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Tea search in the URL. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.