Is it possible in Cypress to invoke the .click() function on an Element without triggering any errors?

I am currently in the process of developing Cypress E2E tests for my Angular application.

One specific page in the app features a table with a link in the third column that is identified by the class name 'link ng-star-inserted'. My goal is to have the test locate a particular row and click on this link.

After some trial and error, I managed to achieve this functionality - the test successfully clicks on the desired link.

However, the implementation feels less than elegant and the .click() method triggers an error (despite functioning correctly).

I am seeking a solution to prevent the .click() method from being flagged as an error.

Below is the code snippet in question...

cy.get(SELECTOR.dataTableBody).should('be.visible')
        .contains('tr', 'Text I am looking for in the row I want')
        .then($row => {
            cy.log('found it');
            cy.log('on row ' + $row.index());

            //Though not ideal, this approach works. I exhausted all other possibilities.
            let cellWithLink = $row.find('td:nth-child(3)');
            cellWithLink.children().get(0).getElementsByClassName('link ng-star-inserted').item(0).click();
            
});

The following image illustrates where the IDE flags the click() method as an error, despite its functionality.

https://i.sstatic.net/xRjxP.png

Thank you in advance!

Answer №1

When examining the test code, the HTML structure resembles something like this:

<table>
  <tbody class="p-datatable-tbody">
    <tr>
      <td></td>
      <td>Some text</td>
    </tr>
    <tr>
      <td>Text I am searching for within the desired row</td>
      <td></td>
      <td>
        <span>
          <a class="link ng-star-inserted">Click me</a></td>
        </span>
    </tr>
  </tbody>
</table>

Upon inspecting the type returned from .getElementsByClassName(), it is evident that it belongs to an HTMLCollection, which represents a collection of elements in a generic manner.

cy.get('table').should('be.visible')
  .contains('tr', 'Text I am looking for in the row I want')
  .then($row => {

    let cellWithLink = $row.find('td:nth-child(3)')

    const link = cellWithLink.children()
      .get(0)
      .getElementsByClassName('link ng-star-inserted')
      // .item(0)
      // .click()

    console.log(link)   // result of getElementsByClassName()
  })

The method item(0) returns an Element that does not support the .click() function (as this type encompasses all elements, not just those that are clickable).

If the TypeScript checker is highlighting this issue (given that Angular is being used), you can attempt type-casting to HTMLElement, which does provide a click() method.

cy.get('table').should('be.visible')
  .contains('tr', 'Text I am looking for in the row I want')
  .then($row => {

    let cellWithLink = $row.find('td:nth-child(3)')
    const link = cellWithLink.children()
      .get(0)
      .getElementsByClassName('link ng-star-inserted')
      .item(0);
      // .click()

    (link as HTMLElement).click()

  })

https://i.sstatic.net/49GRi.png


Simplifying the Complexity

Your test initially involves Cypress queries, then transitions to jQuery queries, and finally utilizes native HTML queries (beginning at .get(0)).

If you prefer to maintain consistency with Cypress throughout, the following command should suffice:

cy.get('table').should('be.visible')
  .contains('tr', 'Text I am looking for in the row I want')
  .find('td:nth-child(3)')
  .find('.link.ng-star-inserted')
  .click()

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

Where could my provider/service have gone missing?

After carefully following the guidelines in the official Angular 2 documentation, I created a CoreModule to handle my services. I also looked into some suggestions on: Providing core singleton services module in Angular 2 Resolving 'No Provider For ...

When trying to import a module in Angular, an error is encountered while using Scully

Exploring the utilization of Scully within my Angular project has presented me with a challenge. In Angular, Modules must be imported in order to use them effectively. However, when attempting to execute Scully through the command line: npm run scully --sc ...

The optimal time to register for events within the Vue lifecycle

Currently, I am developing a Vue2 component using vue-component that includes a subcomponent. Here is an example: <note :bus="bus" :itemId="selectedId"></note> The subcomponent contains the following code snippet: <textarea v-model="text" ...

Define the base URL for the Angular ClientApp hosted by the ASP.NET Core WebApi

After setting up an ASP.NET Core project that serves an Angular app using various methods like services.AddSpaStaticFiles(), app.UseSpaStaticFiles(), and app.UseSpa(), I encountered a challenge. The issue is that the application is currently being served ...

Analyzing bundle files with Angular CLI output

Currently, I am utilizing Angular CLI to develop a production app by using the --prod switch. The resulting bundle is generated in the dist directory. Is there a method to determine which classes and functions have been included in the final bundle after ...

Implementing TypeScript for augmented styling properties in a component - a guide

I have custom components defined as follows: import React from 'react'; import styled from '../../styled-components'; const StyledInput = styled.input` display: block; padding: 5px 10px; width: 50%; border: none; b ...

Unleashing the power of dynamic data imports in a Node.js application

My goal is to utilize the require function in a node/express application with typescript to import a json file. Here's how I attempted it: const url = `./data/${resource}.json`; const data = require(url); However, I encountered the error Cannot find ...

Require type parameter to be of enum type

I have a specific goal in mind: // first.ts export enum First { One, Two, Three } // second.ts export enum Second { One, Two, Three } // factory.ts // For those unfamiliar, Record represents an object with key value pairs type NotWorkingType ...

Creating a dynamic selection in Angular without duplicate values

How can I prevent repetition of values when creating a dynamic select based on an object fetched from a database? Below is the HTML code: <router-outlet></router-outlet> <hr> <div class="row"> <div class="col-xs-12"> & ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

Issues with Angular ng-bootstrap tabset component not functioning as expected

{ "name": "ModalWindow", "version": "1.0.0", "repository": { "type": "git", "url": "" }, "scripts": { "build": "webpack --mode production", "start": "webpack-dev-server --mode development --open" }, "license": "MIT", "depend ...

Incorporate a CSS framework into the Angular vendor bundle

My current situation : The website is built with Angular 4 Started using Angular Starter Kit Utilizing Semantic UI as the CSS framework The challenge I'm facing : Integration of Semantic UI into webpack is not having any impact. Steps I've ...

Guide to implementing dynamic custom validations in Angular 2 using ReactiveForms

I have a specific requirement where I need to create logic that dynamically assigns object array data to an input control. Additionally, I want to update my array based on user input and trigger validation to ensure there are no duplicate entries. I am uti ...

Ways to showcase information retrieved from an API onto an Angular Material card

The process involves calling two different APIs. The first API gathers user information such as name, ID, and the IDs of applications where the user is registered. The second API retrieves details from each application based on its ID. Despite successfully ...

Exclude specific fields when updating a document in Firebase using the update()

Currently, I am storing a class in Firebase by using the update() function. Is there a way to stop specific fields (identified by name) of the object from being saved to the Firebase database? It's similar to how we use the transient keyword in Java ...

Creating a constructor that assigns values by using interfaces that are built upon the class

Looking at this interface/class example export interface MyErrorI { something: boolean; } export class MyError extends Error implements MyErrorI { public something = false; constructor(message: string, key: keyof MyErrorI ) { super(m ...

Accessing the currently operating WS server instance with NodeJS

After successfully setting up a basic REST API using NodeJS, ExpressJS, and routing-controllers, I also managed to configure a WebSocket server alongside the REST API by implementing WS. const app = express(); app.use(bodyParser.json({limit: "50mb"})); a ...

Tips for isolating the filtering process to a specific search box in Angular, rather than filtering the entire dataset

I have a collection of data with individual search boxes, but when I enter information in one search box, it gets applied to all search boxes. I want to be able to filter the data in specific search boxes. Code Snippet: <div *ngFor="let item of data"& ...

I am struggling to extract data from the spawned Node.js child process. What am I overlooking?

Trying to utilize a spawned command-line process for lzip in order to expand an lzipped data stream due to the lack of suitable native JavaScript tools. Succeeded in achieving this by working with files and file descriptors, although cumbersome to handle ...

Getting Angular 2 and Ionic 2 to play nice together: is it worth the effort?

Recently, I attempted to create a glossary app using Ionic 2 and encountered numerous challenges when incorporating the http service. The Angular 2 tutorials had been updated, configuring the mock server proved difficult, and the Ionic 2 documentation offe ...