Cypress, encountering issues with If/Else or Switch Case implementations

My current challenge involves adding else if / switch case in my test. The issue I am facing is that when the initial 'if' condition fails, it does not go into the else if statement. This problem persists in both else if statements and switch cases.

module.exports.selectEnviroment = function(env) {
  switch (env) {
    case 'alpha':
      cy.get('[role="presentation"]')
        .find('[href="#/company-detail/5bb3765e64f66ca0027e15245"]')
        .click();
      break;
    case 'beta':
      cy.get('[role="presentation"]')
        .find('[ng-href="#/company-detail/5bb62c019ee36000273a6e2b"]')
        .eq(0)
        .click();
      break;
  }
}

When it comes to selecting the appropriate case based on the environment, it seems to encounter a problem where it doesn't do so as expected.

it('Booking should be done using invoice', () => {
  cy.visit(`${blah_URL}#/xyz/`);
  let env = blah.split('.')[1];
  selectEnviroment(env);
});

The situation arises when switching between different cases based on the environment selection.

if (cy.get('[role="presentation"]').find('[ng-href="#/company-detail/5bb62c019ee36000273a6e2b"]')) {
  cy.get('[role="presentation"]')
    .find('[ng-href="#/company-detail/5bb62c019ee36000273a6e2b"]')
    .eq(0)
    .click();
} //alpha
else if (cy.get('[role="presentation"]').find('[ng-href="#/company-detail/5bae05a39af4a90027fcdf43"]')) {
  cy.get('[role="presentation"]')
    .find('[ng-href="#/company-detail/5bae05a39af4a90027fcdf43"]')
    .eq(0)
    .click();
} //QA
else if (cy.get('[role="presentation"]').find('[ng-href="#/company-detail/5b855022323d37000f48bcdc"]')) {
  cy.get('[role="presentation"]')
    .find('[ng-href="#/company-detail/5b855022323d37000f48bcdc"]')
    .eq(0)
    .click();
} //Gamma
else if (cy.get('[role="presentation"]').find('[ng-href="#/company-detail/5bb62ccf5cb043002737d929"]')) {
  cy.get('[role="presentation"]')
    .find('[ng-href="#/company-detail/5bb62ccf5cb043002737d929"]')
    .eq(0)
    .click();
}

it('flight booking should be done using new credit card', () => {
  cy.visit(`${COCKPIT_URL}#/company-list/`);
  selectEnviroment();
});

Check out this failure message for reference

Answer №1

When utilizing Cypress commands, it's important to understand that they do not immediately produce results. Instead, calling a Cypress function adds a command to be executed at a later time.

The .then() method was designed for situations like this, allowing you to add code to execute right after the preceding command in the chain:

cy.get('.myDiv').then(elem => {
    // elem is a jQuery object
    console.log(elem.text());
    if (elem.text() == 'Some text') {
        // perform an action
    else {
        // ...
    }
}

I highly recommend exploring the introductory guide to Cypress in the documentation. Understanding how Cypress operates is crucial for writing effective Cypress code, as it differs from other testing frameworks.

Answer №2

Although it may not be directly related, switching between environments can be achieved by following the steps below:

1. Navigate to Cypress/plugin/index.js and insert the code snippet provided:

const envConfig = require('../support/config');

/* eslint-disable no-param-reassign */
module.exports = (on, config) => {
  config.baseUrl = envConfig(config.env.APP_ENV).baseUrl;

  return config;
}
  1. Create a new file named "config.js" within the cypress/support directory, then add the content below:

    `const config = { prod: { baseUrl: '' }, qa: { baseUrl: '' }, dev: { baseUrl: 'http://localhost:8080' } }

    module.exports = typeof Cypress !== 'undefined' ? config[Cypress.env('APP_ENV')] : env => config[env];`

  2. In the cypress/commands folder, utilize this method for login functionality:

    Cypress.Commands.add('login', (username, password) => {
          cy.visit(Cypress.config('baseUrl'))
          cy.url().then(url => {
            if (
              url.indexOf('authorization.oauth2') !== -1 ||
              url.indexOf('auth-corp-aws') !== -1
            ) {
              cy.get('#username').type(Cypress.env('auth_username'))
              cy.get('#password').type(Cypress.env('auth_password'), { log: false })
              cy.get('.ping-button.normal.allow').click()
              cy.wait(1000)
            }
          })
        })

  3. To execute tests in different environments, use the following commands:

    "cy:e2e:qa_env": "CYPRESS_APP_ENV=qa cypress run --headed --browser chrome",
           "cy:e2e:dev_env": "CYPRESS_APP_ENV=dev cypress run --headed --browser chrome",
           "cy:e2e:prod_env": "CYPRESS_APP_ENV=prod cypress run --headed --browser chrome",

Answer №3

it('performs a different action depending on the button's class', () => {
  // RUN THIS TEST MULTIPLE TIMES
  // IT MAY RETURN TRUE OR FALSE.

cy.get('button').then(($btn) => {
   if ($btn.hasClass('active')) {
   // do something when active
   } else {
   // do something else
   }
 })
})

If your element displays random text such as Initiated and Completed, you can handle it this way:

cy.get('.value-text').then($el => {
        // $el is a jQuery object
        console.log($el.text());
        if ($el.text() == 'Initiated') {
 
            cy.get('.edit_status > #cg-icon').click()
        } else {
             // Perform another action here.
        }
    })

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

Error occurred due to an improperly formatted authorization header while attempting to upload an object to S3 using the JavaScript SDK

When attempting to upload an object to Amazon S3 using their JavaScript SDK, I encounter the following error message: <Error> <Code>AuthorizationHeaderMalformed</Code> <Message>The authorization header is malformed; the reg ...

Updating an array in JavaScript with a dynamically generated key name while working in the ReactJS framework

I have multiple dropdown menus, and when I select an option from any of them, I want to store the selected value in the component state. The onChange function that I call looks like this: function handleSelect(event) { console.log(event.target.value); ...

NodeJS: Speed up your workflow by compressing video files

In my quest to enhance the performance of my application, I am seeking ways to compress images and videos to their smallest possible size without sacrificing quality. This process is known as lossless compression. While the imagemin package has proven eff ...

Having trouble importing a React component from a different directory?

I have included the folder structure for reference. Is there a way to successfully import the image component into the card component? No matter which path I try, I keep encountering this error: ./src/Components/Card/Card.js Module not found: Can't ...

Exploring an XML document with HTML

I have an XML file that is paired with an XSL file. The resulting output can be located here. I am working on creating an HTML webpage where users can input a search query, such as 'Year < 2009', into a search box. The table above will then d ...

Javascript promises executing in a mixed-up sequence

Utilizing Javascript's native Promise, I created a modified version of fs.readFile called readFileAsync. This function reads and parses a JSON file, returning the object when resolving. function readFileAsync(file, options) { return new Promise(fun ...

Ensure the left and right screen widgets remain fixed in their positions as the user scrolls down the page using the spacebar

Currently, I have a webpage that showcases products with a large height attribute. I am looking for a way to make the page scroll down when the user hits the space bar to view more products. However, I want my screen widgets such as the shopping cart and ...

What could be causing getStaticProps to receive an incorrect slug value?

Currently, I am encountering an issue with obtaining the correct slug in getStaticProps(). My goal is to retrieve the translated slug for a specific page (for example: the about page). The getStaticPaths() function is able to generate the correct object. ...

What is the best way to integrate JavaScript and Python for seamless collaboration?

I'm looking to create a bidirectional communication model between JavaScript and Python. The idea is for JavaScript to handle data processing, send it to Python for further processing, and then receive the results back from Python. However, I'm u ...

`Shifting a spherical object from point A to point B along its axis`

I am currently working on a project that involves rotating a sphere from point A to point B on itself. After finding Unity3d code for this, I came across the following solution: Quaternion rot = Quaternion.FromToRotation (pointA, pointB); sphere.transform ...

Unable to retrieve Objects from JSON

Here is a JSON object I received: [{"model": "pricing.cashflow", "pk": 1, "fields": {"value": 4.0, "date": "2016-09-09"}}, {"model": "pricing.cashflow", "pk": 2, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 3, "fiel ...

Passing a Javascript variable to the NAME attribute of an HTML <a href> tag: Steps to do it efficiently

I need assistance with passing a JavaScript variable to the NAME attribute of an HTML tag. Let's consider this script example: <script> var name = "Click here!"; </script> My goal is to pass the variable to some code in order for <a ...

Picture is not showing up on my MVC software

Within a table containing multiple other tds, I am having an image tag. <table class="MyClass"> <tr> <td> @Html.LabelFor(m => m.ShopName) </td> <td> @Html.TextBoxFor(mode ...

Purging information from JavaScript object

Looking for a way to remove just one piece of data from a JavaScript object in my React app. Here's the structure of the object: state = { data: [] } const contactData = { Datas: { name: "william", email: "<a href="/cdn-cgi/l/email-pr ...

Top technique for creating an XMLHttpRequest instance

Which technique is recommended for generating an XMLHttpRequest object? The method should be compatible with all modern browsers. ...

Stopping Angular Route Alteration Depending on Routing Conditions

I have been searching everywhere for a solution to this issue. My goal is to be able to access the routing parameters collection and prevent the route from loading if a certain parameter is missing. I have tried using preventDefault in $routeChangeStart, b ...

Improving Javascript Arrays for Easier Reading

A dataset has been organized into a table format as shown below: +------+---------+----+----+----+----+-------+----------+ | Year | Subject | A | B | C | F | Total | PassRate | +------+---------+----+----+----+----+-------+----------+ | 2015 | Maths ...

Enabling the acceptance of blank values within an HTML5 date input field

When using an HTML5 date input for a field that corresponds to a nullable datetime column in the database, how can one avoid setting an empty value in the input field? In my AngularJS application, the ng-model is connected to a scope variable with an init ...

Font in Three JS not loading properly

I'm attempting to use TextGeometry in my project to incorporate text. var shape = new THREE.TextGeometry( 'Hello, World!', { size: 60, height: 20, curveSegments: 3, font: 'helvetiker', weight: ' ...

The button remains active in Internet Explorer 10 and cannot be disabled

The button has been specified as <input type="button" id="disable" disabled="disabled" value="Upload" /> However, the appearance of the button does not show it as disabled in Chrome, Firefox, and Safari. Additionally, in Internet Explorer, the bu ...