Using the if else and hasClass statements for validations in Cypress testing

I am struggling to validate the titles for a certain component. Here is my specific Cypress code snippet:

it('Confirming the correctness of all tile titles', () => {
    cy.get('.bms-scoreboard__game-tile')
      .each(($el) => {
        if($el.hasClass('bms-scoreboard__game-tile--cancelled')) {
            $el.get('.bms-scoreboard__game-tile-status--cancelled')
               .invoke('text')
               .then((text) => {
                  expect(text).equals('Cancelled')
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--pre-game')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                    const gameTime = text.split(" ").pop()
                    expect(['AM', 'PM']).to.include(gameTime)
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--final')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                   const finalTitle = text.trim()
                   expect(finalTitle).to.be.oneOf(['Final','Final (OT)'])
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--ongoing')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                   const ongoingTitle = text.trim()
                   expect(ongoingTitle).equals('Ongoing')
               })
        }
    })
})

An error message pops up saying: 'Cannot read properties of undefined (reading 'invoke')'.

The test runs smoothly when just using the if block alone.

Answer №1

You have the option to make it more concise by utilizing jQuery operators.

$el.find(...) is effective as $el represents a jQuery object.

Additionally, consider switching from .invoke('text') to .text().

cy.get('.bms-scoreboard__game-tile')
  .each(($el) => {

    if ($el.hasClass('bms-scoreboard__game-tile--cancelled')) {

      // Streamline processes using jQuery operators here
      const text = $el.find('.bms-scoreboard__game-tile-status--cancelled').text()
      expect(text).equals('Cancelled')
    }

    if ($el.hasClass('bms-scoreboard__game-tile--pre-game')) {
      const text = $el.find('.bms-scoreboard__game-time--en').text()
      const gameTime = text.split(" ").pop()
      expect(['AM', 'PM']).to.include(gameTime)
    }

    if ($el.hasClass('bms-scoreboard__game-tile--final')) {
      const text = $el.find('.bms-scoreboard__game-time--en').text()
      const finalTitle = text.trim()
      expect(finalTitle).to.be.oneOf(['Final','Final (OT)'])
    }

    if ($el.hasClass('bms-scoreboard__game-tile--ongoing')) {
      const text = $el.find('.bms-scoreboard__game-time--en').text()
      const ongoingTitle = text.trim()
      expect(ongoingTitle).equals('Ongoing')
    }
  })

Answer №2

Whenever you use $el.get(), make sure to wrap the $el before calling .get(). This is because when $el is returned from your initial cy.get(), it is a JQuery<HTMLElement> and falls outside of the Cypress chain.

Furthermore, after wrapping $el, you can utilize .find() to look for elements within the wrapped element.

cy.get('.bms-scoreboard__game-tile')
      .each(($el) => {
        if($el.hasClass('bms-scoreboard__game-tile--cancelled')) {
             cy.wrap($el)
               .find('.bms-scoreboard__game-tile-status--cancelled')
               .invoke('text')
               .then((text) => {
                  expect(text).equals('Cancelled')
               })
...

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

Creating a unique navigation route in React

My application has a consistent layout for all routes except one, which will be completely different from the rest. The entire application will include a menu, body, footer, etc. However, the one-off route should be standalone without these elements. How ...

When going through an array using jquery, only the final object is returned

I am diving into the world of jQuery and dealing with what seems to be a basic issue. <input type="text" name="text1" value=""></input> <input type="text" name="text2" value=""></input> <input type="text" name="text3" value=""&g ...

Trigger Polymer() callback when the element is displayed

Is there a way to implement a callback in the Polymer({}) object that triggers every time the element is displayed? ready doesn't fit the criteria as it's called during the initial page load when the element is created. I'm looking for an ...

The simultaneous use of trackball controls and GUI is not compatible

When I click on them, the GUI changes together and I have looked at other answers. However, I am not sure where to put the listener. I tried putting the listener in render(), but it still doesn't work. How can I fix my code? This coding is related to ...

Integrating Whatsapp cloud API with a React web application allows for seamless communication between

I'm currently in the process of integrating my web application with the WhatsApp cloud API. While I've had success sending test messages, I am now looking to incorporate variables as outlined in the API documentation. However, I seem to be encoun ...

Can you provide guidance on utilizing the Login Event within the Electron Framework?

I need some assistance in understanding the functionality of the Event: 'login' feature within the Electron Framework. Is this similar to the Password Autofill/Remember Password feature typically found in web browsers? I'm interested in util ...

The evaluate function is not functioning as expected

Code: console.log(propertyName); console.log(eval(this.state.propertyName)) console.log(this.state.DriverFirstName); Output: DriverFirstName undefined fsdfds I am attempting to access a variable defined by a string value (propertyNa ...

Guide to making a Typescript interface by combining elements from two separate interfaces without utilizing inheritance

Programming Language: Typescript I am looking to combine the properties of two interfaces as the value of an indexable-type within a third interface. Interface 1: export interface Employee { id: string name: string } Interface 2: export interfa ...

Guide to displaying database results in an HTML dropdown menu by utilizing AJAX technology

Greetings! As a newcomer to the realms of PHP and AJAX, I am currently on a quest to showcase the outcomes of a query within an HTML dropdown using AJAX. Let's delve into my PHP code: $pro1 = mysqli_query("select email from groups"); I made an attemp ...

Unveiling the Power of Ionic and React for Component Repetition

I'm having trouble figuring out how to repeat my component multiple times using react in Ionic. Can someone assist me with this? Here's an example: In my Component.tsx file, I have the following code: import React from 'react'; import ...

Trouble encountered while trying to utilize a Promise to define a global variable

I am attempting to populate a global variable using a function and then call subsequent functions after the data is retrieved. Below is the current code I have: $(function () { var jsonData = {}; var dataRetrievalPromise = function () { r ...

Utilizing Browserify routes and configuring Webstorm

When building my project using gulp and browserify, I made use of path resolution for easier navigation. By following this guide, I configured browserify as shown below: var b = browserify('./app', {paths: ['./node_modules','./src ...

Displaying JSON data obtained from two separate arrays in AngularJS - is it possible?

I want to display the value of my Json element, "Baru20151","Lama20151","Baru20152","Lama20152", but I'm unsure how to do it. The element is fetched from 2 arrays, for the "Baru20151" elements, "20151" is obtained from the "isimasa" array in my Jso ...

My custom font is not compatible with the browser on my asp.net site

I'm having trouble embedding my own font in my .aspx file. Google Chrome and Firefox don't seem to support the font, while IE does. Can someone please provide guidance on how to successfully embed the font in an asp.net page? Below is my code: ...

I am encountering difficulties displaying the image and CSS files from another folder in my HTML with Node.js

I am facing difficulty in establishing a connection between my front-end and back-end using node.js. As a result, the website only displays the HTML code without linking to the CSS or image files. Here is the folder structure: root -src •pi ...

Collecting numerous user-input data from dynamically generated fields

I am working on a simple form in Laravel where users can add multiple forms dynamically using AJAX. Here is the link to my code on jsfiddle: dynamic adding field by user Below is the HTML structure: <form id="paramsForms"> {{csrf_f ...

Best practices for integrating JavaScript with PHP and MySQL

When it comes to inserting data into a MySQL database from JavaScript, I typically use AJAX with jQuery's $.POST function and PHP's mysqli function. This allows me to send the data to a PHP script which then inserts it into the database. Here is ...

Is it possible for a div with fixed position to still have scrolling functionality

My fixed positioned div (#stoerer) appears to be moving while scrolling, although it is just an optical illusion. Check out this visual explanation: view gif for clarification Below is the code snippet in question: <div id="stoerer"> <button ...

Developing a Vue.js API integration

I am struggling to understand why my code is not working as expected. My goal is to retrieve photos from a random dogs API, but something seems to be going wrong. Take a look at the code below. export default { data() { return { posts: [], ...

changing the css transformation into zoom and positioning

My goal is to incorporate pinch zoom and panning using hardware-accelerated CSS properties like transform: translate3d() scale3d(). After completing the gesture, I reset the transform and switch to CSS zoom along with absolute positioning. This method ensu ...