Search code examples
javascriptreactjschakra-ui

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?


Solution

  • 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,
        })),
      };
    });