Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chakra ui unit test with useMediaQuery

I have the following simple test:

jest.mock("@chakra-ui/react", () => ({
  useMediaQuery: jest.fn().mockImplementation(() => ({
    isMobile: false,
  })),
  chakra: jest.fn(),
}))

describe("TopUp card", () => {
  test("should render correctly", () => {
    const { getByTestId } = render(<TopUp {...propsPhysicalProduct} />)

    expect(getByTestId(testIds.TOP_UP_CARD)).toBeInTheDocument()
    expect(getByTestId("test-id")).toBeInTheDocument()
  })
})

when I run it I get the following:

enter image description here

enter image description here

I suspect this is happening because I have been trying to mock "useMediaQuery" which is used inside the component to establish a condition.

COMPONENT:

export const TopUp: React.FC<Props> = (props) => {
  const { item } = props

  if (!item?.variant) return null

  const [isMobile] = useMediaQuery([hookBreakpoints.mobileMax])
  const binIcon = <BinIcon />

  return (
    <CardLayout
      dataTestId={testIds.TOP_UP_CARD}
      cardContent={
        <>
          <Stack display="flex" flexDirection={isMobile ? "column" : "row"}>
...

is there a way to just mock "useMediaQuery" without having to mock all of Chakra?

like image 743
Aessandro Avatar asked Dec 18 '25 10:12

Aessandro


1 Answers

You can use jest.requireActual(moduleName)

jest.mock("@chakra-ui/react", () => {
  // --> Original module
  const originalModule = jest.requireActual("@chakra-ui/react");

  return {
    __esModule: true,
    ...originalModule,
    useMediaQuery: jest.fn().mockImplementation(() => ({
         isMobile: false,
    })),
  };
});
like image 59
lissettdm Avatar answered Dec 20 '25 23:12

lissettdm