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

When trying to deploy to Heroku, node-gyp encounters an issue installing [email protected] and ultimately fails to rebuild

I am currently facing an issue with deploying a nodejs application on Heroku due to the node-gyp rebuild error associated with the base64 library. I have successfully run the application locally, but deployment on Heroku seems to be problematic. Any sugges ...

Failed to load JSON data from the factory

Recently, I started learning AngularJS and have been struggling to fetch JSON data from a factory. The error message I keep getting is not very helpful: TypeError: Cannot read property '1' of null This is the module I am working with: var app ...

What is the best way to showcase content using Chakra-ui SideBar in a React Application?

After exporting the SideBar, I imported it into my App.jsx SideBar.jsx 'use client' import { IconButton, Avatar, Box, CloseButton, Flex, HStack, VStack, Icon, useColorModeValue, Text, Drawer, Draw ...

Join the geomarkers in two datasets using connecting lines

I am currently developing a leaflet.js map incorporating two distinct sets of JSON data layers stored as js-files. The first dataset comprises the geographical locations of various newsrooms along with their respective IDs, while the second dataset contai ...

I am looking to display the results table on the same page after submitting a form to filter content. Can you provide guidance on how to achieve this?

Could someone provide guidance on how to approach the coding aspect of my current issue? I have a search form that includes a select form and a text box. Upon submission, a table is generated with results filtered from the form. Should I utilize a sessio ...

Modify the text in a paragraph by clicking on a link using JQuery and HTML

I'm attempting to implement a straightforward action, but I'm facing some challenges. My navigation bar consists of a few links followed by a text section. What I aim for is that when I click on a link, the paragraph of text should change to refl ...

The drop-down menu remains visible even after clicking outside of it

I've written a script that works when clicked, but it doesn't hide when clicked outside of it. $(document).ready(function() { //Translate(); //caling Language Translater function $("#translate_image").attr('href', base_url) ...

Triggering a JavaScript function upon the alteration of a Dojo auto-complete widget's value

I'm encountering an issue with calling a javascript function when the value of a Dojo auto completer changes. Despite trying to call the function through the "onChange" attribute, it doesn't work as expected. Within the javascript function, my ...

Tips for utilizing a unique JavaScript function with Mongoose's findByIdAndUpdate by incorporating $set:

Is it possible to update a database document using a custom JavaScript function? I am aware of the traditional method where you find -> update the document with JavaScript -> save, but this can lead to issues with concurrent data updates. Below is an examp ...

Adjusting the Connection header in a jQuery ajax request

I've been attempting to modify the Connection header using the code below, but so far, I haven't had any success jQuery.ajax({ url: URL, async: boolVariable, beforeSend: function(xhr) { xhr.setRequestHeader("Connection ...

A Vue component library devoid of bundled dependencies or the need for compiling SCSS files

My current challenge involves the task of finding a way to publish our team's component library. These components are intended to be used by various internal applications within our organization. I have specific requirements: The library must be acc ...

What is the process for bundling a separate JavaScript file with Webpack5?

I am new to the world of webpack. I have 2 javascript files and I want to designate one as the main entry file. However, for the other file, I only want to include it in specific files. For example, looking at the file structure below, main.js is my entr ...

First time blur update unique to each user

By using ng-model-options="{ updateOn: 'blur' }", I can delay model updating until the user clicks out of an input field. This helps prevent constantly changing validation states while initially entering data. However, if a user revisits a field ...

Guide to displaying or hiding elements based on the number of selected checkboxes

When only one checkbox is checked, all buttons in the head-btn class should be displayed. By default, only the add folder and upload buttons are shown. If a user selects two checkboxes, the share button should be hidden. If they uncheck one of the checkbo ...

Vue framework fails to recognize the spread operator when used with WebPack

The code snippet below was recommended in this particular answer. import { mapActions } from 'vuex' export default { vuex: { getters: { activeDataRow: state => state.activeDataRow }, actions: { updateData, resetData } }, methods: ...

Are there any JQuery events that can detect alterations in the list of children elements within an element?

Is there a JQuery event available that can detect changes in the size of an element collection, such as growth or reduction resulting from adding or removing child elements? ...

Expanding rows in Angular UI-Grid: Enhancing user experience with hover functionality

Struggling to add a hover effect to the rows in an Angular UI grid. The goal is for the entire row to change background color when hovered over, but with an expandable grid that includes a row header, applying CSS rules only affects either the row header o ...

Having trouble with Vue image source file paths?

Having an issue with loading an image via file_path on Vue. When using a hardcoded path, it works fine. Refer to the sample code below: JavaScript function getRestaurantsbyId(id) { var restaurants = { "1" : { "name": "xxxx", ...

Exploring an array using bluebird promises

I am currently facing an issue where I need to iterate over an array containing promises. My goal is to multiply all the values in the array by 2 and then return the updated array: var Bluebird = Promise.noConflict(); var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ...

Using regular expressions to validate input in Javascript

Seeking assistance to validate an input text using the pattern <some_string>:<some_string> in JS/JQuery. For instance: A110:B120 AB12C:B123 I understand this might seem overly simplistic, but any guidance would be greatly appreciated. ...