I have a ShadCN Select
component that is abstracted into a CustomSelect
component for reusability. I am trying to test the click functionality of the options
and assert the text content on the Select
button but I’m faced with this error
Unable to find an element with the text: /latest products/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, script, style
<body>
<div>
<div
class="min-w-40"
>
<button
aria-autocomplete="none"
aria-controls="radix-:r7:"
aria-expanded="false"
class="flex h-10 items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 w-full"
data-state="closed"
dir="ltr"
role="combobox"
type="button"
>
<span
style="pointer-events: none;"
>
All Products
</span>
<svg
aria-hidden="true"
class="lucide lucide-chevron-down h-4 w-4 opacity-50"
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="m6 9 6 6 6-6"
/>
</svg>
</button>
</div>
</div>
</body>
I have been trying to fix this issue in the last hour but I haven’t been lucky enough yet. Below is what my test file looks like:
import { screen, render } from "@testing-library/react";
import ProductSortMenu from "../product-sort-menu";
import userEvent from "@testing-library/user-event";
import { useRouter } from "next/navigation";
jest.mock("next/navigation", () => {
const replace = jest.fn();
return {
useSearchParams: () => new URLSearchParams(""),
usePathname: jest.fn().mockReturnValue("/products"),
useRouter: jest.fn().mockReturnValue({ replace }),
};
});
describe("ProductSortMenu", () => {
it("render the select menu component", () => {
render(<ProductSortMenu />);
const selectElement = screen.getByRole("combobox");
expect(selectElement).toBeInTheDocument();
});
it("updates the url when the selected option changes", async () => {
const user = userEvent.setup();
const { replace } = useRouter();
render(<ProductSortMenu />);
const selectButtonElement = screen.getByRole("combobox");
expect(selectButtonElement).toHaveTextContent(/all products/i);
expect(replace).toHaveBeenCalledTimes(0);
await user.click(selectButtonElement);
const latestProductsOption = await screen.findByText(
/latest products/i,
{},
{ timeout: 3000 }
);
await user.click(latestProductsOption);
expect(selectButtonElement).toHaveTextContent(/latest products/i);
expect(replace).toHaveBeenCalledTimes(1);
expect(replace).toHaveBeenCalledWith("/products?sort_by=created_at_desc");
});
});
Please note: The error is thrown when I tried to access the latestProductOption variable. Also, this is what my actual component looks like:
"use client";
import React from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import CustomSelect from "../shared/custom-select";
type SelectValues =
| "all products"
| "oldest products"
| "latest products"
| "lowest price"
| "highest price";
export default function ProductSortMenu() {
const searchParams = useSearchParams();
const pathname = usePathname();
const { replace } = useRouter();
const onValueChangeHandler = (value: SelectValues): void => {
const params = new URLSearchParams(searchParams);
if (value === "lowest price") {
params.set("sort_by", "price_asc");
} else if (value === "highest price") {
params.set("sort_by", "price_desc");
} else if (value === "oldest products") {
params.set("sort_by", "created_at_asc");
} else if (value === "latest products") {
params.set("sort_by", "created_at_desc");
} else {
params.delete("sort_by");
}
replace(`${pathname}?${params.toString()}`);
};
return (
<div className="min-w-40">
<CustomSelect
options={[
"All Products",
"Latest Products",
"Oldest Products",
"Lowest Price",
"Highest Price",
]}
defaultValue="all products"
placeholder="Sort By"
label="Sort products"
onValueChange={onValueChangeHandler}
/>
</div>
);
}
Any pointer to why I am experiencing this error would be greatly appreciated.