Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

173
Views
Cypress: How to spy a method called by a button click

I'm using Vue3 + Vite + Cypress. Using Vue3 script setup SFC syntax. I have a component:

<template>
  <div>
    <button data-cy="testBtn" @click="btnClick()">
      Click
    </button>
  </div>
</template>

<script setup lang="ts">
function btnClick():void {
  console.log('clicked');
}
</script>

How can I spy on btnClick so that I can assert that it has been called when I do cy.get('[data-cy="testBtn"]').click();?
I have tried:

describe('Test', () => {
  it.only(`Test`, () => {
    mount(TestComponent, {
      props: {
        device: TestComponent
      }
    });

    cy.vue().then((wrapper) => {
      const test = cy.spy(wrapper.vm, 'btnClick');
      cy.get('[data-cy="testBtn"]').click();
      expect(test).to.be.called;
    });
  });
});

but I get an error Attempted to wrap undefined property btnClick as function

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

Looks like a bug in cy.spy() when used with component test.

This "manual" spy worked for me

it.only('', () => {
  mount(TestComponent)
    .then(() => {                  // wait for mount to complete

      // spy on click handler
      let called;
      const original = Cypress.vueWrapper.vm.btnClick
      Cypress.vueWrapper.vm.btnClick = () => {
        called = true
        original()
      }

      cy.get('[data-cy="testBtn"]').click()
        .then(() => expect(called).to.eq(true))
    })
});
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs