我正在使用 Material-UIuseMediaQuery()
我的组件之一中的函数来确定size
用于 a 的道具<Button>
在组件内。
我正在尝试测试它在玩笑测试中是否按预期工作,但是我当前的实现不起作用:
describe("Unit: <Navbar> On xs screens", () => {
// Incorrectly returns `matches` as `false` ****************************
window.matchMedia = jest.fn().mockImplementation(
query => {
return {
matches: true,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn()
};
}
);
it("renders as snapshot", async () => {
const width = theme.breakpoints.values.sm - 1;
const height = Math.round((width * 9) / 16);
Object.defineProperty(window, "innerWidth", {
writable: true,
configurable: true,
value: width
});
const { asFragment } = render(
<Container backgroundColor={"#ffffff"}>
<Navbar />
</Container>
);
expect(asFragment()).toMatchSnapshot();
const screenshot = await generateImage({
viewport: { width, height }
});
expect(screenshot).toMatchImageSnapshot();
});
});
describe("Unit: <Navbar> On md and up screens", () => {
// Correctly returns `matches` as `false` ****************************
window.matchMedia = jest.fn().mockImplementation(
query => {
return {
matches: false,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn()
};
}
);
it("renders as snapshot", async () => {
const width = theme.breakpoints.values.md;
const height = Math.round((width * 9) / 16);
Object.defineProperty(window, "innerWidth", {
writable: true,
configurable: true,
value: width
});
const { asFragment } = render(
<Container backgroundColor={"#ffffff"}>
<Navbar />
</Container>
);
expect(asFragment()).toMatchSnapshot();
const screenshot = await generateImage({
viewport: { width, height }
});
expect(screenshot).toMatchImageSnapshot();
});
});
我正在测试的组件(删除了不相关的部分):
const Navbar = () => {
const theme = useTheme();
const matchXs = useMediaQuery(theme.breakpoints.down("xs"));
return (
<Button size={matchXs ? "medium" : "large"}>
Login
</Button>
);
};
export default Navbar;
正在回归matches
as false
对于第一个测试,即使我已将其设置为返回 true。我知道这一点是因为它正在生成屏幕截图,并且我可以看到按钮大小设置为large
对于第一次测试,应将其设置为medium
.
它在生产中按预期工作。
我如何正确地进行模拟useMediaQuery()
在玩笑测试中?