javascript - 为 material-ui 实现 createMatchMedia()。我正在使用材质 ui 隐藏组件来隐藏按钮,同时我正在尝试测试它们
问题描述
我正在使用 React-testing-library getByText 来查找一个按钮,该按钮被名为 Hidden 的材质 ui 组件隐藏。由于 RTL 找不到它,Material ui 在https://material-ui.com/components/use-media-query/#testing有一个实现。但我不知道如何实现它来简单地找到一个按钮。删除隐藏后,该按钮就位于,我只是不确定如何在我的测试中使用他们的 createMatchMedia() 进行查询。
Hidden 组件将我的按钮隐藏在 959px 和 down 处。
import React from "react"
import { render } from '../../../../test/test-utils'
import Collections from "./Collections"
import userEvent from '@testing-library/user-event'
import mediaQuery from 'css-mediaquery'
function createMatchMedia(width: any) {
return (query: string): any => ({
matches: mediaQuery.match(query, { width }),
addListener: () => {},
removeListener: () => {},
});
}
type CollectionsProps = React.ComponentProps<typeof Collections>
const baseProps: CollectionsProps = {
setValue: () => {},
setSelectedIndex: () => {},
pageStyle: {},
pageAnimations: {transition : {}, variants: {}},
motions: {animate:'', initial: '', exit: ''},
jumpTo: (jumpingTarget: string | number | Element): void => {}
}
const renderUI = (props: Partial<CollectionsProps>) =>
render(<Collections {...baseProps} {...props} />, {})
describe('When a filter is clicked', () => {
beforeAll( () => {
window.matchMedia = createMatchMedia(window.innerWidth)
})
let { getByText } = renderUI({})
test('items shown are only related to the picked Category', () => {
userEvent.click(getByText(/Team Colors/))
})
})
解决方案
RTL 不是这里的问题。问题出在jsdom中,它没有实现matchMedia()
. Jest 在内部使用 jsdom 并且没有现有的matchMedia()
媒体查询将匹配 Material UI 的Hidden API。
- 你可以通过首先安装 NPM 包css-mediaquery和@types/css-mediaquery来解决这个问题。
- 然后像这样创建一个模拟
matchMedia
:
// matchMedia.mock.ts
export const createMatchMedia = (width: number) => (query: string): MediaQueryList => ({
matches: mediaQuery.match(query, { width }),
media: query,
onchange: null,
addListener: () => jest.fn(),
removeListener: () => jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn()
});
window.matchMedia = createMatchMedia(window.innerWidth);
export default {};
setupTest.ts
在(您的 Jest 测试设置文件)中导入上面的模拟文件,如下所示:
// setupTests.ts
import './__mocks__/matchMedia.mock';
...
- 像往常一样编写测试。无需使用
beforeAll()
来创建新的window.matchMedia
. 模拟文件会为您处理这些问题。
推荐阅读
- xml - WPF,C#获取响应xml到对象
- swift - UserInfo={NSDebugDescription=字符 0 周围的值无效。}
- javascript - 在 EJS 页面中使用 Object.keys()
- php - MySQL LEFT JOIN - 如何处理记录与 PHP 不匹配的情况
- odoo-13 - 仅在 odoo 13 企业版中隐藏编辑按钮管道最后阶段
- kotlin - 用 !! 抛出自定义空断言 Kotlin 中的运算符?
- algorithm - 跟随的时间复杂度是多少?
- python - 为什么我从 Twitter 中提取关键字的代码没有打印任何内容?
- r - 将点转换为 sf R 中宽度 x km 和高度 y km 的矩形多边形
- html - 关于 robots.txt 禁止参数 URL