【问题标题】:enzyme simulate 'click' doesn't work when it should酶模拟“点击”在应该时不起作用
【发布时间】:2018-03-30 14:09:20
【问题描述】:

我正在使用 Jest 和 Enzyme 测试表单组件,但无法让点击模拟工作。供参考:Button 是一个样式化的 rebass Button,并以如下形式存在:

<Button
  type="reset"
  disabled={pristine || submitting}
  onClick={() => onClose(dirty)}
>

这是失败的测试:

 it('should handle the onClose event', () => {
      const onCloseSpy = jest.fn();
      const renderedComponent = mount(renderFormUtil({ onClose: onCloseSpy }));
      expect(onCloseSpy).not.toHaveBeenCalled();
      console.log(renderedComponent.find(Form).props().onClose);
      renderedComponent
      .find(Button)
      .first()
      .simulate('click');
    expect(onCloseSpy).toHaveBeenCalled();
  });

这里需要注意的是,如果我将模拟行替换为以下内容:

renderedComponent
  .find(Button)
  .first()
  .props()
  .onClick();

然后突然我的测试通过了。这怎么可能?如果 onClick 属性正确,那是不是意味着点击事件没有正确调用该属性?

【问题讨论】:

  • 为什么在一种情况下使用.find(ButtonSubmit) 而在另一种情况下使用.find(Button)?我不知道Button 是什么样子,但我不希望得到相同的结果,因为您正在测试两个不同的组件。
  • 对不起,它们是同一个组件——为了简化,我的意思是去掉组件名称中的“提交”一词

标签: javascript jestjs enzyme


【解决方案1】:

不清楚这两个.find 是否选择了相同的组件,因为每个都使用不同的选择器。再加上您使用的是.first(),无法通过示例代码确定订单。
您可以尝试使用更具体的选择器,避免使用.first() 并仅使用.find 获取所需的组件。为此,您可以为特定的ButtonSubmit 添加id,并使用如下选择器:
.find('ButtonSubmit[id="foo"]')

【讨论】:

  • 抱歉,我刚刚编辑了问题——不应该有 ButtonSubmit。为了提出这个问题,我去掉了名称的那一部分,这样它会更简单,但显然没有做彻底的工作。他们应该选择相同的元素,AFAIK。
猜你喜欢
  • 1970-01-01
  • 2018-01-18
  • 2018-11-05
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2019-11-11
  • 2017-02-06
相关资源
最近更新 更多