Cypress: Uncovering the method invoked by a button click

I'm currently utilizing Vue3 with Vite and Cypress. My Vue3 component utilizes the script setup SFC syntax. Below is the code snippet for my component:

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

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

The issue I'm facing is how to spy on the btnClick function in order to verify that it has been called when executing

cy.get('[data-cy="testBtn"]').click();
. Here's what I have tried so far:

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

Unfortunately, this approach results in an error message stating

Attempted to wrap undefined property btnClick as function
.

Answer №1

Seems like there may be a glitch in cy.spy() when utilized with component testing.

This custom spy method worked successfully for me

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

      // spying 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))
    })
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to create a web application by utilizing HTML5 and REST, and then seamlessly transfer the front-end code to a mobile app using Cordova

Can a mobile application be developed from a web portal using Cordova or similar frameworks? The web portal will consist of: HTML5 for front-end J2EE for back-end with JAX-RS Is it feasible to extract pages from the web portal and integrate them into a ...

What is the best way to add to a variable in jQuery?

I have the following piece of code: var golden_site = '<div id="golden_site"></div>'; $('.form_content').append(golden_site); var lookup = '<input type="text" name="lookup" value="test">'; Can anyone explai ...

Sanitize input data prior to using express-validator in a Node.js application

In my Node.js project, I am utilizing the V4 syntax of express-validator as recommended: const { check, validationResult } = require('express-validator/check'); const { matchedData } = require('express-validator/filter'); Additionally ...

How to convert deeply nested object structures containing arrays in JavaScript

Despite the less-than-desirable name of this inquiry, the question is fairly straightforward. I have a particular object: let test = { date1: [ { time: 1, value: 5, }, { time: 2, value: 6, }, ], date2: [ { ...

Notifying the view with a SignalR message from the controller upon event trigger

Just starting out with SignalR and attempting to set up a notification for a specific event triggered by an API. What I've attempted: Hub: public class NotificationHub : Hub { private static IHubContext hubContext = GlobalHost.Connectio ...

How come the font size and div elements combine when I drag and drop the items?

Recently, I decided to create my own drag and drop game. The game is almost complete, but there's one issue. When I try to drop the items into the designated "Drop Items Here" area, their style changes abruptly to mimic the text. For example: https: ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Issue with setting and showing the PHP data array within the vue.js variable

I am encountering an issue with transferring an array of data from a PHP session variable to a Vue.js variable Here is how I am trying to assign an array of data to a Vue.js variable: permissions:['<?php echo json_encode($_SESSION['permission ...

jqueryajax function returns a boolean value upon completion

Recently, I developed a container method to handle an ajax request: function postRating(formData) { $.ajax({ type: "POST", url: '/api/ratings', data: formData }) .done(function () { return true ...

What is the method for retrieving an array or object that contains a collection of files designated for uploading within the jQuery file upload plugin?

Currently, I have successfully integrated a form into my Rails site and set up the jQuery file upload plugin. The upload form functions properly with the ability to select multiple files and utilize all ajax upload features. However, a challenge I am faci ...

Exploring Vue's "is" Attribute with Web Components

I've encountered an issue while trying to utilize a web component that extends an existing element using the "is" attribute tag within Vue. The problem is that Vue takes this attribute and transforms it into a custom element. While I still want Vue t ...

Sharing information between components in Angular 4 and .NET Core applications

I am new to Angular and .NET Core. I have successfully created a web api using .NET Core, which is called from an Angular 4 application. Currently, everything is working smoothly. However, after submitting a form that inserts records into the database, I w ...

Establish Vue and the Vue CLI

I'm currently in the process of setting up a new Vue project. I started off by installing @vue/cli using the following command: PS D:\OpenServer\domains\vue3-example> npm install -g "@vue/cli" Next, I attempted to create t ...

Having issues with django-autocomplete-light triggering JavaScript errors

My implementation of django-autocomplete-light is causing some issues with rendering autocomplete options. There is a section on the website where it functions perfectly, but in another section, it only works partially. The autocomplete options display c ...

Firebase Cloud Functions - Deleting the eldest offspring

I have created an onWrite cloud function that listens for updates made by a user. My goal is to delete the oldest child if there are more than three children present in the database. Here's where I currently stand: exports.removeOld = functions.datab ...

Having trouble locating an external Javascript file in a Node.JS/Express app with Jade template?

In my Node.JS/Express app, I am using the Jade template engine. The issue arises when trying to reference a server-side Javascript file named common_routines. Despite placing the Javascript file in the directory above my views directory and referencing it ...

Javascript text validation is malfunctioning as the alert message fails to appear

Looking for a simple form validation script: <script language=”javascript”> function checkForm(register) { if (""==document.forms.register.FNAME.value){ alert("Please fill out this field!"); document.forms.register.FNAME.focus( ...

Events related to key press timing in HTML 5 canvas

Currently, I am developing a game similar to Stick Hero for Android using HTML5. I am working on the code that will capture the time of key press (specifically the right arrow key with ASCII 39) in JavaScript and expand a stick accordingly. <!doctype h ...

Having trouble with Vuejs uploading multiple images when not using a CDN?

Hello! I am currently experimenting with implementing this specific plugin for uploading multiple images using vue.js. Below you can find the code snippet that I have been working on. <!DOCTYPE html> <html lang="en> <head> &l ...

How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this https://i.sstatic.net/E2e3S.png scenario. Is there a method that can redirect the user back to the same page without using Authguard or a ...