首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在功能组件中使用方法回调测试按钮

在功能组件中使用方法回调测试按钮
EN

Stack Overflow用户
提问于 2020-12-31 10:06:38
回答 1查看 89关注 0票数 2

我正在尝试使用酶来测试react组件。我无法测试IconButton组件上的点击,并且当我模拟点击时,函数不会被调用。

这就是在外部组件上定义IconButton的方式。

代码语言:javascript
复制
var IconButton = function (props) {
    return (React.createElement(IconButton$1, { color: 'default', onClick: props.onClick, disabled: props.disabled, size: props.size, onMouseDown: props.onMouseDown }, props.children));
};export{Button,IconButton};

这就是我如何在我的应用程序中使用它。

代码语言:javascript
复制
import React, {useState, useEffect} from 'react';
import { Drawer } from '@material-ui/core';
import ExpandLessIcon from '@material-ui/icons/ExpandLess';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import { IconButton } from '@mycomponent/button';

export default function Component1 {
  const classes = useStyles();
  const [open, setOpen] = useState(true);

  const handleClick = function (event) {
    if (event) {
      setOpen(!open);
    }
    else {
      return;
    }
  };

  return (
    <Drawer>
      <div className="classname1">
          <IconButton onClick={(e) => handleClick(e)} className={classes.button, "iconBtn"}>
            {open ? <ExpandLessIcon data-test="lessIcon" /> : <ExpandMoreIcon data-test="moreIcon" />}
          </IconButton>
      </div>
    </Drawer>
  );
}

这是我用来模拟点击图标按钮的测试。我还尝试了另一种方法来检查handleClick是否被调用,但仍然失败。

代码语言:javascript
复制
    const wrapper = shallow(<Component1 />);

    it('Test the button click', () => {
        expect(wrapper.containsMatchingElement(<ExpandMoreIcon />)).toBeTruthy()
        const element = wrapper.find(".iconBtn")
        const mockEvent = {target: {}};
        element.simulate('click', mockEvent)
        expect(wrapper.containsMatchingElement(<ExpandLessIcon />)).toBeTruthy()
    })
EN

回答 1

Stack Overflow用户

发布于 2020-12-31 19:17:14

尝试更改此行:

代码语言:javascript
复制
const element = wrapper.find("button").at(0);

或者你可以通过来自debug()的className找到它

代码语言:javascript
复制
const element = wrapper.find(".MuiButtonBase-root MuiIconButton-root");

请注意,在这种情况下,您将模拟单击实际的html按钮。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65515807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档