测试是否调用了 const 模态组件

IT技术 reactjs jestjs enzyme antd
2021-05-27 20:43:39

我有一个页脚组件,上面有几个按钮。所有这些按钮都使用Messageconst,它是一个 antd 模式:

消息.jsx

import { Modal } from 'antd';

const { confirm } = Modal;

export const Message = (text, okayHandler, cancelHandler) => {
  confirm({
    title: text,
    okText: 'Yes',
    cancelText: 'No',
    onOk: okayHandler,
    onCancel: cancelHandler,
  });
};

export default Message;

页脚.jsx

class Footer extends Component {
  state = {
    from: null,
    redirectToReferrer: false,
  };

  cancelClicked = () => {
    Message('Return to the previous screen?', () => {
      this.setState({ redirectToReferrer: true, from: '/home' });
    });
  };

render() {
    const { redirectToReferrer, from } = this.state;

    if (redirectToReferrer) {
      return <Redirect to={{ pathname: from }} />;
    }
    return (
      <Card style={footerSyles}>
        <Button
          bounds={`${(3 * width) / 7 + (7 * width) / 84},5,${width / 7},30`}
          text="CANCEL"
          type="primary"
          icon="close"
          actionPerformed={this.cancelClicked}
        />
</Card>
//actionPerformed is actually onClick, it's taken as a prop from my <Button /> component. Card is an antd component while button is not.

我只是想测试当Button被点击时,cancelClicked被调用。如果可能,我想测试在模态上单击“确定”按钮时状态是否正确更改。我的测试如下,但测试失败,因为没有调用函数:

页脚测试

const defaultFooter = shallow(<Footer position="relative" bounds="10,0,775,100" />);

test('Footer should open a popup when cancel button is clicked, and redirect to home page', () => {
  const instance = defaultFooter.instance();
  const spy = jest.spyOn(instance, 'cancelClicked');
  instance.forceUpdate();
  const p = defaultFooter.find('Button[text="CANCEL"]');
  p.simulate('click');
  expect(spy).toHaveBeenCalled();
});

我也尝试过使用 mount 而不是浅,但仍然没有调用 spy。

1个回答

“常见问题”部分simulate说“即使名称暗示这是模拟实际事件,.simulate() 实际上将根据您提供的事件定位组件的props。例如,.simulate('click' ) 实际上会得到 onClick props并调用它。”

该行为可以在此处此处Enzyme源代码中看到

所以该行p.simulate('click');最终试图调用不存在onClick属性,Button所以它基本上什么都不做。

来自 Airbnb 开发人员的这篇文章建议直接调用 props 并避免simulate.

在这种情况下,您可以actionPerformed像这样直接调用该属性:

p.props().actionPerformed();