简体   繁体   中英

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:

在此处输入图像描述

在此处输入图像描述

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM