vue.jscypresssinon

Cypress spy not being called when VueJS component emits event


I'm trying to follow the guide here to test an emitted event.

Given the following Vue SFC:

<script setup>
</script>

<template>
  <button data-testid="credits" @click="$emit('onCredits')">Click</button>
</template>

and the following Cypress test:

import { createTestingPinia } from '@pinia/testing';

import Button from './Button.vue';

describe('<Button />', () => {
  it('renders', () => {
    const pinia = createTestingPinia({
      createSpy: cy.spy(),
    });

    cy.mount(Button, {
      props: {
        onCredits: cy.spy().as('onCreditsSpy'),
      },
      global: {
        plugins: [pinia],
      },
    });

    cy.get('[data-testid=credits]').click();
    cy.get('@onCreditsSpy').should('have.been.called');
  });
});

My test is failing with

expected onCreditsSpy to have been called at least once, but it was never called

It feels weird passing in the spy as a prop, have I misunderstood something?


Solution

  • OP also asked this question in cypress github, but failed to mention the solution. As is mentioned here:

    Vue has some special rules around the "on" prefix. The event being emitted is generally "eventName" and the prop registering for that event would be "onEventName". In your example, you would emit credits and the handler would be onCredits. If you update your SFC to emit credits I think it should work