Cypress tip: how to stub an alert

Posted on: 29 January 2021
javascript
random header of a mountain

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. Simple enough, but took me some Googling to find how to do it, so I'm adding it here so it's more available.

How to do it

This is my snippet of code, used in a unit test in this case

Given a component like:

<Component data-test-id="element" handleOnClick={() => {alert('Hello')}} />

We can test the onClick like this:

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