Locate an item and add it to my online cart for purchase

Seeking assistance with my journey in learning javascript and cypress. I am having trouble locating an item on a page and adding it to the shopping cart.

After using .find, I am not receiving any response. There are no errors in cypress, but the item is not being added to the cart, and cy.log isn't displaying anything either.

/// <reference types="Cypress"/>

     it ('CountElements', () => {
        cy.visit ('https://www.saucedemo.com/v1/inventory.html')

        cy.get('.inventory_list >')
        cy.get('.inventory_list >').as ('PopularProducts')
        cy.get('@PopularProducts').should('have.length', 6)
    })

   it ('Adding "top" element to the shopping cart from the main page', function (){
        cy.visit ('https://www.saucedemo.com/v1/inventory.html')

        cy.get('.inventory_list >').as ('PopularProducts')

        cy.get('@PopularProducts')
        .find ('.inventory_item_name')
        .each(($el,index,$list) => {
            if($el.attr('.inventory_item_name') == 'Sauce Labs Onesie'){
                cy.log ('Item found as intended')
                cy.get ('@PopularProducts').eq(index).contains('ADD TO CART').click()
            } 
        })
    })
    })
I have been able to successfully add the item to the cart by explicitly specifying its position in the list, but I need the functionality to work without knowing the exact location.

it ('Adding "top" element to the shopping cart from the main page', function (){

        cy.visit ('https://www.saucedemo.com/v1/inventory.html')

        cy.get('.inventory_list >').as ('PopularProducts')

        cy.get('@PopularProducts')
        .find ('.inventory_item_name')
        .each(($el,index,$list) => {
            if($el.attr('.inventory_item_name') == 'Sauce Labs Onesie'){
                cy.log ('Item found as intended')
                
            } 
            
        })
        cy.get ('@PopularProducts').eq(5).contains('ADD TO CART').click()
    })

Answer №1

A confusion has arisen between text and attribute, consider switching the order of the .contains() command with the .find() command.

You could try implementing it like this:

cy.find('.inventory_list .inventory_item', 'Sauce Labs Onesie')
  .contains('button:contains("ADD TO CART")').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

When a label is clicked, the ng-change event is not triggered on the corresponding radio button

I developed a custom directive that allows you to select a radio button by focusing on its label and pressing the spacebar. However, although the radio button is checked, the ng-change function action() does not get triggered. Below is the HTML code snipp ...

"CodeIgniter error: stdClass object does not have the specified property" - troubleshooting controller problem

Upon inheriting the code for this website, I encountered some difficulties understanding certain aspects of it. The issue revolves around the creation of blog pages. When attempting to create a new blog page through the admin site, I encountered an error b ...

Tips for embedding Apache Superset visualizations into an Angular 7 app: Overcoming hurdles with authentication and headers

I am currently working with Apache Superset to create charts. I am looking to embed these charts in my Angular 7 application using an iframe. One major problem I encountered is an authentication failure with the following error message: Refused to display ...

Is there a way to restrict the number of times I can utilize slideToggle function?

When I continuously click on a div element in an HTML website that triggers the .slideToggle() method, it will keep opening and closing for as many times as I click. The problem arises when I stop clicking, as the <div> continues to toggle open and c ...

NodeJS Streams: Delay in data transfer with Readable.pipe()

My understanding was that Stream.Readable.pipe() would immediately pipe data as it receives it, but I'm facing unexpected results while trying to create my own streams. const { Writable, Readable } = require("stream"); const writable = new ...

How can you determine the location of a point on the perimeter of a regular polygon?

Imagine you have a pentagon, with numbered sides like moving around a clock: https://i.sstatic.net/pWqdFtfg.png Starting from the center of the polygon, how can you calculate the position of a point in these locations (along the edge of the polygon): At ...

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...

Tips for uploading arrays in Node.js´s:1. Use the `

Can someone help me with posting multiple arrays simultaneously? Here is what I am trying to achieve: { name:"John Snow", detail: [ {size: "M", total: 5, color: "red"}, {size: "S", total: 2, color: "bl ...

Store the fetched data as JSON in the local storage

Struggling to find a solution after reading several articles, I am working on fetching a large JSON from an API and I want to cache the response in the localStorage. The goal is for the script to check for an object with the requested ID in the cached JSON ...

Bringing in the jqGrid library with Meteor using NPM

I am currently working on a project using Meteor and I want to incorporate the free-jqgrid library. However, I am unsure of the correct way to import this library... I have tried: import 'free-jqgrid'; import jqGrid from 'free-jqgrid&apo ...

What is the best way to add an array of objects to MongoDB using Golang and the official MongoDB Driver?

I'm currently facing an issue with inserting an array of objects and adding new objects to the existing array. The problem arises when I insert the array, resulting in an object nested inside an array within the parent array. Below is a snippet of my ...

An invalid argument error occurred in line 4618 of jQuery version 1.4.2, with a value of NaNpx specifically

There seems to be a common exception occurring in jQuery.extend as follows: Error Message: Invalid argument. Line Number: 4618 Character Position: 4 Error Code: 0 URI: The issue I am facing is that amongst our development team, only my machine is experie ...

When comparing two state arrays in React, it is important to note that they will not be considered equal and return a boolean (True

As I attempt to compare two arrays stored in my state, my goal is to set a boolean variable to "true" if they match. However, my current if statement fails to detect equality between the arrays. I'm performing this comparison within a setInterval() f ...

What is the best way to connect a series of checkboxes within a form utilizing Angular?

I created a form with checkboxes that allow users to select multiple options. However, when I submit the form, instead of receiving an array of objects representing the checked checkboxes, I'm not getting anything at all. Here is what I see in the co ...

Creating an HTML table on-the-fly leads to the opening of a fresh new webpage

Has anyone encountered this issue before? I have a math table coding function, which runs when a button is clicked. However, when I click the button, the table appears on a new page instead of on the same page. <!doctype html> <html> <h ...

having trouble displaying album artwork

Encountering an unusual error in my music player implementation on the website. All functions of the music player are working perfectly fine. First, let's take a look at the error: TypeError: Cannot read properties of undefined (reading 'cover&a ...

Is it feasible to have multiple versions of React coexisting in a monorepo?

I have a monorepo set up with npm workspaces: ├─ lib │ └─ Foo └─ src ├─ App └─ Web I am looking to upgrade the Web package to React 18 while keeping App on React 17 My current dependencies are as follows: ├─ lib │ └ ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...

Converting a JavaScript function to TypeScript with class-like variables inside: a step-by-step guide

During the process of converting a codebase to TypeScript, I encountered something unfamiliar. In particular, there are two functions with what appear to be class-like variables within them. The following function is one that caught my attention: const wai ...

Unexpected Behavior Arises from Axios Get API Request

Below is a functional example in my CodePen showing what should be happening. Everything is working as intended with hard coded data. CodePen: https://codepen.io/anon/pen/XxNORW?editors=0001 Hard coded data: info:[ { "id": 1, "title": "Title one ...