|
| 1 | +import { render, screen } from "@testing-library/react"; |
| 2 | +import userEvent from "@testing-library/user-event"; |
| 3 | +import { describe, expect, it, vi } from "vitest"; |
| 4 | +import { NativeOption, NativeSelect } from "./NativeSelect"; |
| 5 | + |
| 6 | +describe("NativeOption", () => { |
| 7 | + it("renders an option with value and text", () => { |
| 8 | + render( |
| 9 | + <select aria-label="Test"> |
| 10 | + <NativeOption value="a">Alpha</NativeOption> |
| 11 | + </select>, |
| 12 | + ); |
| 13 | + expect(screen.getByRole("option", { name: "Alpha" })).toHaveValue("a"); |
| 14 | + }); |
| 15 | +}); |
| 16 | + |
| 17 | +describe("NativeSelect", () => { |
| 18 | + it("renders options as children", () => { |
| 19 | + render( |
| 20 | + <NativeSelect aria-label="Pick one"> |
| 21 | + <NativeOption value="1">One</NativeOption> |
| 22 | + <NativeOption value="2">Two</NativeOption> |
| 23 | + </NativeSelect>, |
| 24 | + ); |
| 25 | + expect( |
| 26 | + screen.getByRole("combobox", { name: "Pick one" }), |
| 27 | + ).toBeInTheDocument(); |
| 28 | + expect(screen.getByRole("option", { name: "One" })).toHaveValue("1"); |
| 29 | + expect(screen.getByRole("option", { name: "Two" })).toHaveValue("2"); |
| 30 | + }); |
| 31 | + |
| 32 | + it("renders a visible label linked to the select", () => { |
| 33 | + render( |
| 34 | + <NativeSelect label="Country"> |
| 35 | + <NativeOption value="us">United States</NativeOption> |
| 36 | + </NativeSelect>, |
| 37 | + ); |
| 38 | + const label = screen.getByText("Country"); |
| 39 | + const select = screen.getByRole("combobox", { name: "Country" }); |
| 40 | + expect(label).toHaveAttribute("for", select.id); |
| 41 | + }); |
| 42 | + |
| 43 | + it("uses a stable id when id prop is passed", () => { |
| 44 | + render( |
| 45 | + <NativeSelect id="country-select" label="Country"> |
| 46 | + <NativeOption value="us">United States</NativeOption> |
| 47 | + </NativeSelect>, |
| 48 | + ); |
| 49 | + expect(screen.getByRole("combobox")).toHaveAttribute( |
| 50 | + "id", |
| 51 | + "country-select", |
| 52 | + ); |
| 53 | + expect(screen.getByText("Country")).toHaveAttribute( |
| 54 | + "for", |
| 55 | + "country-select", |
| 56 | + ); |
| 57 | + }); |
| 58 | + |
| 59 | + it("forwards extra props to the select", async () => { |
| 60 | + const user = userEvent.setup(); |
| 61 | + const onChange = vi.fn(); |
| 62 | + render( |
| 63 | + <NativeSelect aria-label="Test" onChange={onChange} data-testid="sel"> |
| 64 | + <NativeOption value="a">A</NativeOption> |
| 65 | + <NativeOption value="b">B</NativeOption> |
| 66 | + </NativeSelect>, |
| 67 | + ); |
| 68 | + expect(screen.getByTestId("sel")).toBeInTheDocument(); |
| 69 | + await user.selectOptions(screen.getByTestId("sel"), "b"); |
| 70 | + expect(onChange).toHaveBeenCalled(); |
| 71 | + }); |
| 72 | +}); |
0 commit comments