【问题标题】:Test React confirmation window using enzyme使用酶测试反应确认窗口
【发布时间】:2016-07-13 09:46:04
【问题描述】:

我在 React 中有一个按钮,当用户点击它时会打开一个简单的确认窗口。在我添加确认方法之前,下面的测试是绿色的。添加确认后它是红色的。我需要如何更改测试以使用附加确认?

React 删除按钮:

const DeleteButton = (props) => {
  const handleDelete = () => {
    if(confirm("Are you sure?")) {
      props.onDelete(props.id)
    }
  };

  return (
      <Button className="btn" onClick={handleDelete}>
        <i className="fa fa-trash-o"></i>
      </Button>
  );
};

这是测试(使用酶):

describe('<DeleteButton />', () => {
  it("deletes the entry", () => {
    const onDelete = sinon.spy();
    const props = {id: 1, onDelete: onDelete};
    const wrapper = shallow(<DeleteButton {...props} />);
    const deleteButton = wrapper.find(Button);

    deleteButton.simulate("click");
    expect(onDelete.calledOnce).to.equal(true);
  });
});

【问题讨论】:

    标签: reactjs enzyme


    【解决方案1】:

    您可以使用sinon.stub 存根confirm

    describe('<DeleteImportButton />', () => {
      it("simulates delete event", () => {
        const onDeleteImport = sinon.spy();
        const props = {id: 1, onDelete: onDeleteImport};
        const wrapper = shallow(<DeleteImportButton {...props} />);
        const deleteButton = wrapper.find(Button);
    
        const confirmStub = sinon.stub(global, 'confirm');
        confirmStub.returns(true);
        deleteButton.simulate("click");
        expect(confirmStub.calledOnce).to.equal(true);
        expect(onDeleteImport.calledOnce).to.equal(true);
    
        confirmStub.restore();
      });
    });
    

    【讨论】:

    • 感谢您的回答。测试仍然返回 false。以防万一您想知道,为了使我的问题更简单,我已从我的问题中删除了导入引用。
    • 你是用真正的浏览器运行测试吗?按业力说?请改用const confirmStub = sinon.stub(global, 'confirm');。并验证是否实际调用了 confirmStub
    • 不,我正在运行npm test,但不涉及任何浏览器。 const confirmStub = sinon.stub(global, 'confirm'); 工作。非常感谢!
    猜你喜欢
    • 2019-01-30
    • 2017-08-16
    • 2017-09-24
    • 1970-01-01
    • 2020-08-22
    • 2020-06-01
    • 1970-01-01
    • 2020-11-17
    • 2017-05-20
    相关资源
    最近更新 更多