Verify if the same attribute is present in various fields using Cypress automation testing

I'm working on a form that contains both disabled and enabled fields.

In my current setup, I have a command that checks for disabled fields:

Cypress.Commands.add("checkElementState", (myselector) {
if(myselector) {

   cy.getBySel(myselector).should('be.disabled')
})

However, this command only checks for one element at a time. How can I modify the code to support multiple testids for the same object?

Is it possible to structure it like this:

cy.checkElementState(myselector: ["first-element", "second-element", "third-element"])

Where first-element, second-element, and third-element are the testids.

Any guidance on how I can achieve this would be greatly appreciated.

Answer №1

Instead of using a loop with .forEach(), you can pass an array of selectors to the function

cy.getBySel(myselector).should('be.disabled")
.

/// <reference types="cypress" />

Cypress.Commands.add("myElementState", (selectors) => {
  selectors.forEach(mySelector => {
    cy.getBySel(mySelector).should('be.disabled')
  });
})

To make it work in Typescript, remember to define the type specifications for Custom Commands in your index.d.ts file.

/// <reference types="cypress" />

declare namespace Cypress {
  interface Chainable {

    getBySel(selector: string, args?: any): Chainable<JQuery<HTMLElement>>;
    myElementState(mySelectors: string[]): Chainable<undefined>;

  }
}


If you use

cy.wrap(selectors).each((selector) => {
in Typescript, you need to specify the type as JQuery<HTMLElement>.

https://i.sstatic.net/26f5j4tM.png

In Javascript, you can directly iterate over the array using .forEach(), but in Typescript, proper coercion is required.

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

Therefore, utilizing .forEach() for arrays of strings is recommended instead of coercing types.

Answer №2

cy.wrap is a powerful tool that allows you to seamlessly insert arrays into your Cypress command chain, resulting in a Chainable<string[]> variable that can be conveniently iterated over using cy.each.

Cypress.Commands.add("checkElementState", (elementList) => {
  cy.wrap(elementList).each((element) => {
    cy.getBySel(element).should('be.disabled')
  });
})
...
cy.checkElementState(['apple', 'banana', 'orange']);

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

Repeated Type Declarations in TypeScript

Recently, I've come across an interesting challenge involving duplicated TypeScript type declarations. Let me explain: In my project A, the dependency tree includes: A->@angular/http:2.3.1 A->B->@angular/http:2.3.1 Both A and B are install ...

What is the reason behind receiving the error message "`Foo` only represents a type, but is being treated as a value here" when using `instanceof` in TypeScript?

As the creator of this code interface Foo { abcdef: number; } let x: Foo | string; if (x instanceof Foo) { // ... } Upon running this code, I encountered an error in TypeScript: 'Foo' is recognized only as a type and cannot be used a ...

Tips for dynamically changing the selected option in a drop-down menu using Angular 5

Currently, I am encountering an issue while attempting to pre-select a value in a dropdown menu using Angular 5. This is the HTML code: <mat-form-field class="col-sm-3"> <mat-select placeholder="State" name="state [formControl]="stateFormCont ...

Only numerical values are permitted, and numbers may not commence with 0 in Angular 4

Hey there, I'm new to Angular 4 and in need of help validating a form field. I want to allow only numbers, but the first digit should not be 0. I've tried different solutions that I found, but none of them worked for me. Could someone please as ...

Creating click event handler functions using TypeScript

I encountered an issue when trying to set up an event listener for clicks. The error message I received was that classList does not exist on type EventTarget. class UIModal extends React.Component<Props> { handleClick = (e: Event) => { ...

Generate fresh instances of object(s) using JSON information

After receiving JSON data from a service call, I am presented with the following structure: myArray: any = [ {item: 'Jelly Beans', areaCode: 321, Company: "Bob's Candy"}, {item: 'Skittles', areaCode: 444, Company: "Jim's Cand ...

Is it possible to deactivate input elements within a TypeScript file?

Is it possible to disable an HTML input element using a condition specified in a TS file? ...

The decode function in MxCodec is failing to properly parse XML data

Currently, I am working on a project using javascript with Angular7 and MxGraph library. I have successfully managed to save the MxGraph model into an XML file with the following code snippet: var enc = new mx.mxCodec(mx.mxUtils.createXmlDocument()); var ...

What is the best way to extract a value from an input within a filter?

I am currently utilizing ngx-easy-table in my application. I am trying to retrieve the input filter value on keyup event, but I have not been able to find any helpful information in the documentation. Does anyone have any insights or suggestions on how to ...

A guide on efficiently utilizing combineLatest and mergeMap for handling multiple subscriptions

As I continue to delve into the world of rxjs, I've encountered an issue with managing multiple subscriptions. Specifically, I'm struggling to extract an ID from a response in order to correctly associate photos with products. create(product) { ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

Is there a way to implement the onClick event within a styled component?

I am experiencing an issue with styling in my code. I want to describe the problem using images. Essentially, when clicking on an image button, I expect the MenuItemContainer to become visible. const MenuItemContainer = styled.div` visibility: hidden; ...

Support for translation of TypeScript files is provided in Angular 7 with i18n

Recent Versions. "@angular-devkit/build-angular": "0.13.4", "@angular-devkit/build-ng-packagr": "0.13.4", "@angular/animations": "7.2.2", "@angular/cdk": "7.2.2", "@angula ...

What is a simple method to convert TypeScript to JavaScript?

Is it possible to eliminate TypeScript-specific keywords from a JavaScript file without using the tsc command, while ensuring that the file remains readable by humans and maintains JSX syntax? ...

Unable to utilize my TypeScript library within JavaScript code

I've hit a roadblock with a seemingly straightforward task and could really use some fresh perspective. I'm currently developing a custom TypeScript library intended for use in both TypeScript and JavaScript projects within our organization. Th ...

Tailwind component library - personalize color schemes for your project's design

I recently created a component library using Tailwind and React, and I've utilized Rollup for building the distribution files. In my tailwind.config.js file, you'll find the following color declarations: const colors = require('tailwindcss/c ...

"Specifying the data type of function parameters in parts

Trying to define a type for a function "factory", the issue arises when the number of arguments in the callback is unknown beforehand. Take a look at the following factory builder: type Fn = (...args: any[]) => any function apply<F extends Fn>(fn ...

Error: Module '...' or its type declarations could not be located

Recently, I attempted to deploy my next.js app on Vercel, only to encounter an error that read: "Type error: cannot find module '...' or its corresponding type declarations." After some investigation, I suspect this error is related to local modu ...

Solving the 'never' type issue in Vue3 and TypeScript for an empty array reference

I am currently in the process of migrating a component from an old Vue project that relies solely on JavaScript to a TypeScript/Vue project, and I have encountered some obstacles along the way. <script lang="ts"> import { computed, ref } fr ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...