使用酶测试反应确认窗口

时间:2016-07-13 09:46:04

标签: reactjs enzyme

我在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);
  });
});

1 个答案:

答案 0 :(得分:5)

您可以使用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();
  });
});