What is the best way to locate the third item in my array using Cypress?

Can you help me with a more flexible code for this method?

static getTemplateItemName() {
  const x = this.templateItem.find('.template-name').contains('Basic elements').scrollIntoView({ensureScrollable: false});
  cy.get('.template-cover').within(() =>
    cy.get('.btn-link-primary').contains('Preview').click({force: true});
};

I am trying to update the code to make it dynamic and not dependent on .eq(2). Any suggestions on how to achieve this?

Below is the HTML structure:

<div _ngcontent-nbr-c91="" class="template-cover">
  <div _ngcontent-nbr-c91="" class="template-description">
    <div _ngcontent-nbr-c91="" class="template-name">
      <p _ngcontent-nbr-c91="" class="text-xs">Basic elements</p> 
    </div>
    <div _ngcontent-nbr-c91="" class="template-actions ng-star-inserted">
      <button _ngcontent-nbr-c91="" class="btn btn-link-primary">Preview</button>
      <button _ngcontent-nbr-c91="" class="btn btn-outline-primary"> Select </button>
    </div>
    <!---->
  </div>
</div>

Thank you!

Answer №1

Instead of using eq(2), you can opt for selecting the parent element to navigate to your template cover element. Once there, you can click on the Preview button by utilizing the within function. Here's an example:

cy.contains('p', 'Basic elements')
  .parent() //template-name
  .parent() //template-description
  .parent() //template-cover
  .within(() => {
    cy.contains('button', 'Preview').click({force: true})
  })

Answer №2

If the Preview and Select buttons you are looking for are specific to the div with the identifier template-cover, then accessing them is simple.

// ensure we are in the correct template
cy.contains('.template-cover', 'Preview')
  .should('be.visible')
  .contains('button', 'Preview')
  .should('be.visible')
  // if your element is obscured, use force:true
  .click({force:true})
  

If the buttons are not unique to the template, we can refer to it by its name.

// ensure we are in the correct template
cy.contains('.template-cover', 'Basic elements')
  .should('be.visible')
  .contains('button', 'Preview')
  .should('be.visible')
  // if your element is obscured, use force:true
  .click({force: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

The reducer within ngrx/store fails to trigger

In my project using combineReducers with "@angular/core": "4.4.3" and "@ngrx/store": "4.0.3", I am facing an issue where the reducers are not being detected after dispatching the actions. It could be due to my lack of experience with ngrx/store. You can ...

Switching the phone formatting from JavaScript to TypeScript

Below is the JavaScript code that I am attempting to convert to TypeScript: /** * @param {string} value The value to be formatted into a phone number * @returns {string} */ export const formatPhoneString = (value) => { const areaCode = value.substr(0 ...

Change the return type of every function within the class while maintaining its generic nature

Looking for a solution to alter the return type of all functions within a class, while also maintaining generics. Consider a MyService class: class CustomPromise<T> extends Promise<T> { customData: string; } interface RespSomething { data ...

Employing square brackets for accessing JSON data in JavaScript

I am facing a requirement where I need to extract the value of the JSON data based on the column specified by the user. for (var k = 0; k < arr.length; k++) { for (var i = 0; i < checkedFilters.length; i++) { console.log("value[columnNam ...

Exploring the relationship between classes and objects within Angular

Is it problematic to use traditional classes and objects in Angular code? For instance, when refactoring to separate specific logic from messy code, I often create a separate file like logic-handler.ts and define a class like so... export class LogicHandle ...

Ways to prevent PySpark from_json from displaying a complete null row when reading a CSV file with JSON typed columns containing null attributes

I'm currently experiencing an issue that I hope to articulate clearly. I'm attempting to parse a CSV file using PySpark. This CSV file contains some JSON columns. The JSON columns have a consistent schema, but the way they are filled varies. Fo ...

Array of Ogre3D scene nodes

I am currently in the process of developing a procedurally generated city using ogre3d. My goal is to have a city spawn when the player approaches a designated area marked as a city. However, I am facing a challenge in storing the buildings within an arr ...

Can you use the useCallback function within a nested callback function?

within component A: const retrieveOnClick = useCallback( (rec: GenericRec): (() => void) => () => { setSelectedRecord(rec); }, [], ); inside component B which is a child of A: const displayRecord = useCallback( (row: Row& ...

Inspect this PHP array using the in_array function

My $checked array is structured as follows: array(2) { [0]=> array(1) { ["id_kategorii"]=> string(1) "2" } [1]=> array(1) { ["id_kategorii"]=> string(1) "4" } } When I loop through the $categories array, it looks l ...

Is there any special significance to the statement x = x in TypeScript/Angular?

The Fontawesome/Angular documentation provides an example of adding an explicit reference, which may not be as convenient as using the library directly. If you value "explicit is better than implicit," then this method might be for you. The example code sn ...

Creating input fields in Angular 2

Can someone guide me on how to sum the values entered in two input fields? Here is my HTML code snippet. I'm not sure if there's anything missing in the ts file. <div class="small-7 columns"> <md-input-container> <input t ...

Error encountered while traversing through a hashtable due to a null pointer

Currently working on creating a hash table in Java and conducting some analysis. One of the tasks at hand involves comparing the number of values that map to the same key in this hash table. To do this, I have decided to use a prime number for this analys ...

What is the reason behind NumberFormat only recognizing four numbers?

Encountering an issue with inputting values into a TextField embedded in NumberFormat. Only three numbers are accepted before the field resets. I aim to divide the value in the TextField by a format based on the selection made in the drop-down menu. For ex ...

Exploring the PHP array following JSON decoding

After successfully loading and decoding a JSON array into a PHP array, I encountered an issue when trying to access specific data within the array. $jsonfile = file_get_contents('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&sym ...

Is there a way to assign a function signature to every property within a class in typescript?

When I am structuring a class to contain all methods related to its functionality, I ensure that all the methods within the class have a specific signature. I attempted to utilize an index signature in this manner: interface rulesType { [key:string]: t ...

Creating a hierarchical structure using JavaScript

In my quest to create a hierarchical tree structure for Category and Sub-category based on the facets provided by SOLR, I have encountered an input in the following format: ['445', 79, '398', 73, '710', 32, '398|760&apos ...

Do PLPGSQL arrays begin indexing at 1?

In my experience, I've noticed that in PLPGSQL the first index of an array starts at 1 by default, which is different from the usual convention of starting at 0 in most programming languages. It piqued my curiosity as to why this is the case and if th ...

How can I transfer a JSON array to a custom element in Angular?

Having trouble passing a JSON array in an angular component (custom element). The code includes looping through the JSON array and setting up the array data in @Inject. Here's an example: Import { Input, Component, ViewEncapsulation, EventEmi ...

Oops! Angular2 couldn't find a provider for HttpHandler

I have been working on implementing HttpCache through an interceptor. Below is the code snippet for caching-interceptor.service.ts: import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http' import ...

When working with Typescript, utilizing `null as string | null` can result in a parsing error that says, "Unexpected token, expected ``,`."

Currently, I am going through a React Toolkit tutorial that incorporates Typescript. During this process, I encountered the usage of initialState: null as string | null, within the code example provided and explained at this specific point in the video: c ...