Skip to content

Checkpoint: Test the Combobox

The Course
•
20 min study

Close the earlier lessons and work from the brief. This is Day 5's combobox, with the same app around it.

The combobox to test React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import Combobox from "./Combobox.jsx"; import { topics } from "./topics.js"; export default function App() { const [chosen, setChosen] = useState(null); return ( <main> <h1>Pick a topic</h1> <Combobox label="Topic" options={topics} onSelect={setChosen} /> <p className="muted">Chosen: {chosen ?? "nothing yet"}</p> </main> ); } import { useId, useState } from "react"; // A text box with a list of suggestions. Focus stays in the input; the // highlighted option is announced through aria-activedescendant. export default function Combobox({ label, options, onSelect }) { const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const [activeIndex, setActiveIndex] = useState(-1); const id = useId(); const listId = `${id}-list`; const matches = options.filter((o) => o.toLowerCase().includes(query.trim().toLowerCase())); const optionId = (index) => `${id}-option-${index}`; function choose(option) { setQuery(option); setOpen(false); setActiveIndex(-1); onSelect(option); } function handleKeyDown(event) { if (event.key === "ArrowDown") { event.preventDefault(); setOpen(true); setActiveIndex((i) => Math.min(i + 1, matches.length - 1)); } else if (event.key === "ArrowUp") { event.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); } else if (event.key === "Enter" && open && activeIndex >= 0) { event.preventDefault(); choose(matches[activeIndex]); } else if (event.key === "Escape") { setOpen(false); setActiveIndex(-1); } } return ( <div> <label htmlFor={`${id}-input`}>{label}</label>{" "} <input id={`${id}-input`} role="combobox" aria-expanded={open} aria-controls={listId} aria-autocomplete="list" aria-activedescendant={open && activeIndex >= 0 ? optionId(activeIndex) : undefined} value={query} onChange={(e) => { setQuery(e.target.value); setOpen(true); setActiveIndex(-1); }} onKeyDown={handleKeyDown} /> {open && matches.length > 0 && ( <ul role="listbox" id={listId} aria-label={label}> {matches.map((option, index) => ( <li key={option} id={optionId(index)} role="option" aria-selected={index === activeIndex} data-active={index === activeIndex} onMouseDown={(e) => e.preventDefault()} onClick={() => choose(option)} > {option} </li> ))} </ul> )} </div> ); } export const topics = [ "Compound components", "Controlled props", "Render props", "Imperative handles", "External stores", "Selectors", "State machines", "Suspense", "Request cache", "Lazy loading", "Profiling", "Windowing", "Activity", "Dialogs", "Comboboxes", ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

The brief

Download the project, set it up as in the first lesson, and write src/Combobox.test.jsx. Render Combobox on its own, with your own options and an onSelect you can check. Cover:

  • typing filters the options, and the list is expanded;
  • Down and Up move the active option, aria-activedescendant points at it, and focus stays in the input;
  • Enter chooses the active option, calls onSelect with it, and closes the list;
  • Escape closes the list and keeps the text;
  • clicking an option chooses it, and focus stays in the input.

Then prove two of your tests can fail: delete onMouseDown={(e) => e.preventDefault()} from Combobox.jsx, and check a test fails; then put it back.

Hint 1: keys

await user.keyboard("{ArrowDown}{Enter}") presses keys on whatever has focus. After user.type(input, ...), that's the input.

Hint 2: the active option

The active option has aria-selected="true", so screen.getByRole("option", { selected: true }) finds it. Compare its id with the input's aria-activedescendant.

Hint 3: a setup function

Five tests render the same thing. A setup() that renders and returns { user, onSelect, input } keeps each test short.

Show one solution
JSX
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test, vi } from "vitest";
import Combobox from "./Combobox.jsx";

const options = ["Selectors", "State machines", "Suspense", "Windowing"];

function setup() {
  const onSelect = vi.fn();
  const user = userEvent.setup();
  render(<Combobox label="Topic" options={options} onSelect={onSelect} />);
  return { user, onSelect, input: screen.getByRole("combobox", { name: "Topic" }) };
}

test("typing filters the options", async () => {
  const { user, input } = setup();

  await user.type(input, "st");

  expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["State machines"]);
  expect(input.getAttribute("aria-expanded")).toBe("true");
});

test("the arrow keys move the active option, and focus stays in the input", async () => {
  const { user, input } = setup();

  await user.type(input, "s");
  await user.keyboard("{ArrowDown}{ArrowDown}");

  const active = screen.getByRole("option", { selected: true });
  expect(active.textContent).toBe("State machines");
  expect(input.getAttribute("aria-activedescendant")).toBe(active.id);
  expect(document.activeElement).toBe(input);
});

test("Enter chooses the active option and closes the list", async () => {
  const { user, input, onSelect } = setup();

  await user.type(input, "su");
  await user.keyboard("{ArrowDown}{Enter}");

  expect(onSelect).toHaveBeenCalledWith("Suspense");
  expect(input.value).toBe("Suspense");
  expect(screen.queryByRole("listbox")).toBeNull();
});

test("Escape closes the list and keeps the text", async () => {
  const { user, input, onSelect } = setup();

  await user.type(input, "s");
  await user.keyboard("{Escape}");

  expect(screen.queryByRole("listbox")).toBeNull();
  expect(input.value).toBe("s");
  expect(onSelect).not.toHaveBeenCalled();
});

test("clicking an option chooses it, and focus stays in the input", async () => {
  const { user, input, onSelect } = setup();

  await user.type(input, "w");
  await user.click(screen.getByRole("option", { name: "Windowing" }));

  expect(onSelect).toHaveBeenCalledWith("Windowing");
  expect(document.activeElement).toBe(input);
});

Without the onMouseDown line, clicking an option chooses it, and focus stays in the input fails: pressing the mouse moves focus to the option first.

Check yourself

  1. Why is result.current read after each step instead of saved once?
  2. Why does Vitest's fake clock need shouldAdvanceTime with Testing Library?
  3. When is mocking a module the right choice, and when is it testing the mocks?

Was this article helpful?

Your response is saved on this device.