Files
web/packages/design-system/lib/components/LinkChips/LinkChips.test.tsx

93 lines
3.1 KiB
TypeScript

import { describe, expect, it, afterEach } from "vitest"
import { render, screen, cleanup } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { LinkChips } from "./LinkChips"
import type { LinkChipsProps } from "./types"
afterEach(() => {
cleanup()
})
const defaultChips: LinkChipsProps["chips"] = [
{ title: "Hotels in Stockholm", url: "/hotels/stockholm" },
{ title: "Hotels in Copenhagen", url: "/hotels/copenhagen" },
{ title: "Hotels in Oslo", url: "/hotels/oslo" },
]
describe("LinkChips", () => {
describe("rendering", () => {
it("renders all chip links", () => {
render(<LinkChips chips={defaultChips} />)
expect(
screen.getByRole("link", { name: "Hotels in Stockholm" })
).toBeTruthy()
expect(
screen.getByRole("link", { name: "Hotels in Copenhagen" })
).toBeTruthy()
expect(screen.getByRole("link", { name: "Hotels in Oslo" })).toBeTruthy()
})
it("renders chip links with correct href attributes", () => {
render(<LinkChips chips={defaultChips} />)
expect(
screen.getByRole("link", { name: "Hotels in Stockholm" }).getAttribute("href")
).toBe("/hotels/stockholm")
expect(
screen.getByRole("link", { name: "Hotels in Copenhagen" }).getAttribute("href")
).toBe("/hotels/copenhagen")
expect(
screen.getByRole("link", { name: "Hotels in Oslo" }).getAttribute("href")
).toBe("/hotels/oslo")
})
it("returns null when chips array is empty", () => {
const { container } = render(<LinkChips chips={[]} />)
expect(container.firstChild).toBeNull()
})
it("handles single chip", () => {
const singleChip = [{ title: "View all hotels", url: "/hotels" }]
render(<LinkChips chips={singleChip} />)
expect(screen.getByRole("link", { name: "View all hotels" })).toBeTruthy()
expect(
screen.getByRole("link", { name: "View all hotels" }).getAttribute("href")
).toBe("/hotels")
})
})
describe("keyboard navigation", () => {
it("allows keyboard navigation between links", async () => {
const user = userEvent.setup()
render(<LinkChips chips={defaultChips} />)
const firstLink = screen.getByRole("link", {
name: "Hotels in Stockholm",
})
const secondLink = screen.getByRole("link", {
name: "Hotels in Copenhagen",
})
await user.tab()
expect(document.activeElement).toBe(firstLink)
await user.tab()
expect(document.activeElement).toBe(secondLink)
})
})
describe("edge cases", () => {
it("handles chips with duplicate titles but different URLs", () => {
const duplicateTitles: LinkChipsProps["chips"] = [
{ title: "Hotels", url: "/hotels/stockholm" },
{ title: "Hotels", url: "/hotels/copenhagen" },
]
render(<LinkChips chips={duplicateTitles} />)
const links = screen.getAllByRole("link", { name: "Hotels" })
expect(links).toHaveLength(2)
expect(links[0].getAttribute("href")).toBe("/hotels/stockholm")
expect(links[1].getAttribute("href")).toBe("/hotels/copenhagen")
})
})
})