使用Enzyme测试React确认窗口

4

我在React中有一个按钮,当用户单击它时会打开一个简单的确认窗口。在添加confirm方法之前,下面的测试是绿色的。添加确认后,测试变成了红色。我需要如何更改测试来与额外的确认一起工作?

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

这里是测试代码(使用enzyme):

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个回答

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();
  });
});

谢谢你的回答。测试仍然返回false。以防你想知道,为了让我的问题更简单,我已经从问题中删除了导入引用。 - Linus
1
你是否在使用真实的浏览器来运行测试?比如说karma?尝试使用const confirmStub = sinon.stub(global, 'confirm');,并验证confirmStub是否被调用。 - Yury Tarabanko
不,我正在运行npm test,没有涉及任何浏览器。 const confirmStub = sinon.stub(global, 'confirm'); 工作正常。非常感谢! - Linus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接