我最近将一个应用程序迁移到了我喜欢的 Material UI v4。
还更新了我们使用 jest/enzyme 运行的测试套件。例如,我现在更喜欢
mount
而不是 shallow
。
一个问题是我找不到测试图标存在的方法。
在撰写本文时,我正在使用所有最新版本的material-ui、react 和 jest/enzyme 等工具。
在MUI源代码中,我在规范文件中看到类似这样的东西:
wrapper.find('svg[data-mui-test="KeyboardArrowLeftIcon"]'
这是在 createSvgIcon 源代码中声明此道具的方式:
<SvgIcon {...props} data-mui-test={`${displayName}Icon`} ref={ref}>
但是,我在
data-mui-test
中的 node_modules
文件中找不到对该 @material-ui/icons/utils/createSvgIcon.js
道具的任何引用:
var Component = _react.default.memo(_react.default.forwardRef(function (props, ref) {
return _react.default.createElement(_SvgIcon.default, (0, _extends2.default)({
ref: ref
}, props), path);
}));
事实上,测试中的
wrapper.debug()
显示 DOM 中不存在该 prop:
[...]
<svg
className="MuiSvgIcon-root"
focusable="false"
viewBox="0 0 24 24"
color={[undefined]}
aria-hidden="true"
role="presentation">
[...]
问题
data-mui-test
属性?为了更好地模仿访问图标的用户体验,请使用
titleAccess
属性:(将 SvgIcon
替换为您实际使用的图标)
<SvgIcon titleAccess="My Icon" />
然后在测试中:
expect(screen.getByTitle("My Icon")).toBeInTheDocument();
data-testid 的标准测试技术适用于这些图标,即:
<Warning color="warning" data-testid="warning-icon" />
然后在你的测试中
expect(documentBody.getByTestId('warning-icon')).toBeInTheDocument();