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.
So I was able to fix the test failure by referencing this Github discussion and a similar implementation can also be found in this stackoverflow answer
Apparently, the Radix UI which the Shadcn UI's Select
component is built on top uses PointerEvent
to trigger the opening of a dropdown menu like the Select
component. Therefore, it is important to create a mock implementation of the PointerEvent constructor to be able to have access to the SelectContent
dropdown component that holds the values of the select options.
It's worthy of mentioning that the two links referenced above used a class-based approach to mocking the PointerEvent
but I decided to transform it to a functional-based approach which currently works well and passes my test.
function createMockPointerEvent(
type: string,
props: PointerEventInit = {}
): PointerEvent {
const event = new Event(type, props) as PointerEvent;
Object.assign(event, {
button: props.button ?? 0,
ctrlKey: props.ctrlKey ?? false,
pointerType: props.pointerType ?? "mouse",
});
return event;
}
// Assign the mock function to the global window object
window.PointerEvent = createMockPointerEvent as any;
// Mock HTMLElement methods
Object.assign(window.HTMLElement.prototype, {
scrollIntoView: jest.fn(),
releasePointerCapture: jest.fn(),
hasPointerCapture: jest.fn(),
});
This is what my full code looks like now:
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 }),
};
});
function createMockPointerEvent(
type: string,
props: PointerEventInit = {}
): PointerEvent {
const event = new Event(type, props) as PointerEvent;
Object.assign(event, {
button: props.button ?? 0,
ctrlKey: props.ctrlKey ?? false,
pointerType: props.pointerType ?? "mouse",
});
return event;
}
// Assign the mock function to the global window object
window.PointerEvent = createMockPointerEvent as any;
// Mock HTMLElement methods
Object.assign(window.HTMLElement.prototype, {
scrollIntoView: jest.fn(),
releasePointerCapture: jest.fn(),
hasPointerCapture: jest.fn(),
});
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();
// Create a custom container for portals in the test
const portalContainer = document.createElement("div");
document.body.appendChild(portalContainer);
render(<ProductSortMenu />, { container: portalContainer });
const selectButtonElement = screen.getByRole("combobox");
expect(selectButtonElement).toHaveTextContent(/all products/i);
expect(replace).toHaveBeenCalledTimes(0);
await user.click(selectButtonElement);
const latestProductOption = screen.getByText(/latest product/i);
await user.click(latestProductOption);
expect(selectButtonElement).toHaveTextContent(/latest products/i);
expect(replace).toHaveBeenCalledTimes(1);
expect(replace).toHaveBeenCalledWith("/products?sort_by=created_at_desc");
});
});
I hope this helps anyone who runs into similar issue.