Testing ShadCN Select with Jest and React testing Library [duplicate]

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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>
</code>
<code>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> </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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");
});
});
</code>
<code>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"); }); }); </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"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>
);
}
</code>
<code>"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> ); } </code>
"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.

2

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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(),
});
</code>
<code>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(), }); </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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");
});
});
</code>
<code>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"); }); }); </code>
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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật