Cypress tip: how to stub an alert
I’ve recently started using Cypress for testing web applications, and even for unit testing. One thing that was not immediately clear to me was how to stub (aka, fake) a basic thing like an alert, so that I can “listen” for this alert to be called, and assert that yes, it was indeed called.
How to do it
This is my snippet of code, used in a unit test in this case
Given a component like:
1 2 3 4 5 |
<MyButton data-test-id="element" onClick={handleOnClick}> Test </MyButton> |
We can test the onClick like this:
1 2 3 4 5 6 7 8 9 10 11 |
it('the "handleOnClick" prop works correctly', () => { const stub = cy.stub() cy.on('window:alert', stub) cy.get('[data-test-id="element"]') .click() .then(() => { expect(stub.getCall(0)).to.be.calledWith('Hello') }) }) |
0
×