问题
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?
React delete button:
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);
});
});
回答1:
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();
});
});
来源:https://stackoverflow.com/questions/38348110/test-react-confirmation-window-using-enzyme