【问题标题】:test icons in SVG format测试 SVG 格式的图标
【发布时间】:2021-02-02 16:34:02
【问题描述】:

如何测试按钮中添加的图标?此按钮触发打开菜单。 menuTriggerLabel 是常量。

import { Button } from '@material-ui/core';
import { ExpandLess, ExpandMore } from '@material-ui/icons';
import React from 'react';

export const myMenuTriggerLabel = 'My menu';

export const MyMenu = () => {
  const [open, setOpen] = React.useState(false);
  const handleToggle = () => {
    setOpen((prevOpen) => !prevOpen);
  };
  return (
    <div>
      <Button onClick={handleToggle} endIcon={open ? <ExpandLess /> : <ExpandMore />}>
        {myMenuTriggerLabel}
      </Button>
    </div>
  );
};

我想测试图标是否为ExpandMore,点击按钮,测试图标是否为ExpandLess,再次点击按钮,测试图标是否为ExpandMore

it('should render proper icon on show and hide', async () => {
  const component = render(<MyMenu />);
  const icon = component.getByText(menuTriggerLabel)
  ???
  

我知道如何点击按钮。我不知道如何断言图标。

【问题讨论】:

  • &lt;ExpandLess /&gt;&lt;ExpandMore /&gt; 的代码是什么?我想您只需将打开图标放在一个 render() 中,将关闭图标放在另一个 render() 中,就可以区分打开和关闭。
  • 你能添加一个jsfiddle,codesnipt链接吗?
  • @M.M.H.Masud 我已经编辑了问题并添加了完整的MyMenu 组件源。

标签: reactjs material-ui react-testing-library react-material


【解决方案1】:

我不熟悉 react-testing 库。 但我喜欢开玩笑+ Enzime。主要思想是通过组件选择来测试它。

可能类似于 jest+Enzime。

const checkOpenState = (tree, state) => {
    expect(!!tree.find(ExpandLess).length).toBe(state)
};
const checkCloseState = (tree, state) => {
   expect(!!tree.find(ExpandMore).length).toBe(state)
};
const toggleState = (tree) => {
   tree.find(Button).props().onClick();
}
it('should render proper icon on show and hide', async () => {
  const component = shallow(<MyMenu />);
  checkOpenState(component, false);
  checkCloseState(component, true);

  toggleState(component);

  checkOpenState(component, true);
  checkCloseState(component, false);

对于 react-testing-library,您可以查看文档并调整我的解决方案)

【讨论】:

  • 在这种情况下,您可以检查 prop 'endIcon' 的值是否正确吗?
  • 我不知道如何使用 React 测试库来做到这一点
  • 明天我会更新我的反应测试库答案)
猜你喜欢
  • 2017-01-03
  • 2019-10-04
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 2015-07-07
  • 2021-11-09
相关资源
最近更新 更多