Jest&material-ui:如何测试特定图标的存在?

2024-02-23

我最近将一个应用程序迁移到我喜欢的 mui v4。

还完成了更新我们使用 jest/enzyme 运行的测试套件。例如我现在喜欢mount代替shallow.

一个问题是我找不到一种方法来测试图标的存在。

在撰写本文时,我正在使用所有最新版本的material-ui、react 和 jest/enzyme 等工具


在MUI源代码中 https://github.com/mui-org/material-ui/blob/58bebd747f8a4cb757b2f05321d56f25bb04821e/packages/material-ui/src/Tabs/TabScrollButton.test.js#L56,我在规范文件中看到类似的内容:

wrapper.find('svg[data-mui-test="KeyboardArrowLeftIcon"]'

这里是在创建SvgIcon https://github.com/mui-org/material-ui/blob/9259aaaebbeded8b9b538a37c4be6094baede348/packages/material-ui-icons/src/utils/createSvgIcon.js#L7来源这个道具是如何声明的:

<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">
[...]

问题

  1. Why is data-mui-testprop 已从生成的 npm 模块代码中删除?
  2. 这仍然是测试图标存在的正确方法吗? (正如 mui 团队成员建议的那样 https://github.com/mui-org/material-ui/issues/15928#issuecomment-497634585)

data-testid 的标准测试技术适用于这些图标,即:

<Warning color="warning" data-testid="warning-icon" />

然后在你的测试中

expect(documentBody.getByTestId('warning-icon')).toBeInTheDocument();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Jest&material-ui:如何测试特定图标的存在? 的相关文章

随机推荐