I am having some issues mocking media queries for show/hide objects on different sizes. I have tried a couple of solutions in stack overflow including this one:
Figuring out how to mock the window size changing for a react component test
The tests always seem to render the mobile view:
<Show above="md">
<ChakraModal isOpen={isOpen} onClose={onClose} {...rest}>
<ModalOverlay />
<ModalContent
{...theme.modal.modalContent}
borderRadius={theme.br05}
w={{ base: `calc(100% - 2 * ${theme.space[4]})`, md: "100%" }}
maxW="xl"
>
{footerCTAs?.length ? (
<ModalFooter
data-testid="modal-footer-desktop"
justifyContent={footerCtaAlignment}
display={ctaOrientation === "vertical" ? "inline-grid" : "flex"}
flexWrap="wrap"
{...theme.modal.modalFooter}
gap={2}
>
{footerCTAs.map(({ label, onClick, variant }) => (
<Button key={label} onClick={onClick} variant={variant} {...isModalButtonFullWidth}>
{label}
</Button>
))}
</ModalFooter>
) : null}
</ModalContent>
</ChakraModal>
</Show>
<Hide above="md">
<ChakraDrawer isOpen={isOpen} onClose={onClose} placement={placement} isFullHeight={isFullHeight}>
<DrawerContent borderTopRadius={theme.br05}>
<DrawerCloseButton alignSelf="end" position="relative" {...theme.modal.drawerCloseBtn} />
{footerCTAs?.length ? (
<DrawerFooter
data-testid="modal-footer-mobile"
justifyContent={footerCtaAlignment}
display="flex"
flexDir="column"
{...theme.modal.drawerFooter}
gap={2}
>
{footerCTAs.map(({ label, onClick, variant }) => (
<Button key={label} onClick={onClick} variant={variant} flexGrow={1} width="100%" h={14}>
{label}
</Button>
))}
</DrawerFooter>
) : null}
</DrawerContent>
</ChakraDrawer>
</Hide>
And here is my test
import React from "react";
import { render } from "@testing-library/react";
import { ChakraProvider, Show, Hide, useBreakpointValue } from "@chakra-ui/react";
import { useMediaQuery } from '@chakra-ui/react';
Object.defineProperty(window, "matchMedia", {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
global.innerWidth= 1200;
jest.mock("@chakra-ui/react", () => {
// --> Original module
const originalModule = jest.requireActual("@chakra-ui/react");
return {
__esModule: true,
...originalModule,
useMediaQuery: jest.fn()
};
});
it.only("renders multiple ctas in vertical orientation on desktop", () => {
(useMediaQuery as jest.Mock).mockReturnValue(false);
const { getByTestId, container } = render(
<ChakraProvider theme={theme}>
<Modal {...modalProps} isOpen footerCTAs={submitAndCancelCTAs} ctaOrientation="vertical">
test
</Modal>
</ChakraProvider>
);
const modalFooter = getByTestId("modal-footer-desktop");
expect(modalFooter).toHaveStyle({ display: "inline-grid" });
});
Does anyone have any thoughts on this?
Thanks