使用酶测试反应确认窗口 [英] Test React confirmation window using enzyme

查看:70
本文介绍了使用酶测试反应确认窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React中有一个按钮,当用户单击它时会打开一个简单的确认窗口。在添加确认方法之前,下面的测试是绿色的。添加确认后,其为红色。我该如何更改测试才能与其他确认一起使用?

I've got a button in React which opens a simple confirmation window when the user clicks on it. Before I added the confirm method, the test below was green. After adding the confirm it's red. How do I need to change the test to work with the additional confirm?

删除按钮:

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

这里是测试(使用酶):

Here is the test (using 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);
  });
});


推荐答案

您可以存根 confirm 使用 sinon.stub

You can stub confirm using sinon.stub.

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

这篇关于使用酶测试反应确认窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆