How to verify a custom event in a Cypress test?

148 Views Asked by At

In my Typescript file I am dispatching a custom event when some information is loaded to the html page.

  dispatchEvent() {
    const myCustomEvent = new CustomEvent('myCustomEvent', {
      id: 123,
    });
    this.dispatchEvent(myCustomEvent);
  }

I can see that the event is dispatched correctly in console so I think I don't need to dispatch it also from Cypress but maybe I'm wrong. Any ideas how to verify that the custom event is emitted and also has the desired data?

1

There are 1 best solutions below

1
On

Component tests

There is an example using change event here Angular examples which uses the createOutputSpy helper utility function from cypress/angular.

You should just be able to substitute your custom event name

import { createOutputSpy } from 'cypress/angular'

it('tests custom event', () => {
  cy.mount(myComponent, {
    declarations: [...],
    componentProperties: {
      myCustomEvent: createOutputSpy<any>('myCustomEventSpy'),
    },
  })
  ...
  // trigger action here, or none if triggered on mounting

  cy.get('@myCustomEventSpy')
    .should('have.been.called')
    .its('firstCall.args.0')
    .should('deep.equal', { id: 123 })
})

e2e tests

If you are performing e2e tests instead of component tests, an event spy might be configured something like this:

cy.visit('/', {
  onBeforeLoad: (win) => {
    win.addEventListener('myCustomEvent', cy.stub().as('myCustomEventSpy'))
  },
})

...
// trigger action here, or none if triggered on page loading

cy.get('@myCustomEventSpy')
  .should('have.been.called')
  .its('firstCall.args.0')
  .should('deep.equal', { id: 123 })