Tips for preventing excessive nesting of .then() when handling API Calls in Cypress

My team and I are currently exploring ways to make dependent API calls in Cypress more readable. Our current code looks like this:

// nested code
      cy.request('GET', myUrl).its('body').then(res => {
        cy.request('GET', res).its('body').then(subRes => {
          cy.request('GET', subRes).its('body').then(subSubRes => {
            expect(subSubRes, myMessage).to.eq(myEvaluation);
          })
        })
      })

We've also considered the following solution, but we don't feel it significantly improves readability:

// less nested code?
      let response;
      let subResponse;
      cy.request('GET', myUrl).its('body').then(res => {
        response = res;
      })
      
      cy.then(() => {
        cy.request('GET', response).its('body').then(subRes => {
          subResponse = subRes;
        })
      })

      cy.then(() => {
        cy.request('GET', subResponse).its('body').then(subSubRes => {
          expect(subSubRes, myMessage).to.eq(myEvaluation);
        })
      })

If you have any ideas on how to avoid creating nested pyramids of logic, please share them with us. Thanks in advance!

Answer №1

Something similar to the following code snippet may be effective:

cy.request('GET', myUrl).its('body')
    .then(res => cy.request('GET', res).its('body'))
    .then(subRes => cy.request('GET', subRes).its('body'))
    .then(subSubRes => {
        expect(subSubRes, myMessage).to.eq(myEvaluation);
    });

This approach should give the desired results.

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

Generating a new display div element using an anchor link

I've set up a div container with a button that, upon clicking, adds a class to an element in my markup causing it to expand and take over the entire screen. Markup before: <section class="isi" data-trigger="toggle" data-trigger-class="isi--show-i ...

A guide to iterating over an array and displaying individual elements in Vue

In my application, there is a small form where users can add a date with multiple start and end times which are then stored in an array. This process can be repeated as many times as needed. Here is how the array structure looks: datesFinal: {meetingName: ...

Storing information within a global variable array or exploring alternative methods

I am currently working on a project in electron / node.js and need assistance with the following tasks: Importing data from excel/csv files Visualizing the data using d3.js Cleaning the data by removing duplicates, etc. Using the data for calcu ...

What are the specific instances in which jQuery Ajax error codes are triggered?

According to the jQuery documentation, there are 4 potential error codes: parserror timeout abort error I have observed that parserror occurs when the response content-type is application/json but jQuery is unable to parse it. Timeout occurs when the s ...

Resolving borderRadius problem in JSS and React JS

UPDATE: Upon further investigation, it appears that each time the component is re-rendered, material-ui's makeStyles gets executed again, while JSS's createUseStyles does not! I have a component that needs to adapt its styling dynamically based ...

Trying to utilize RegEx for my project, but feeling stuck on how to solve my problem

^\d{1,12}$|(?=^.{1,15}$)^\d+\.\d{1,2}$ This is the current regular expression I am using. I need to adjust the maximum limit to 100,000,000,000 with an option for two decimal places. Additionally, I would like users to be able to inpu ...

Having trouble formatting the Modal form in Bootstrap when using AngularJS

The code runs successfully, but I am struggling to get the desired output. You can find the code here. <div class="modal fade" id="signup" tabindex="-1" role="dialog"> <div class="modal-dialog modal-sm"> <div class="modal-content"> ...

Implementing specific CSS styles for different routes in Angular 5: Use Bootstrap CSS exclusively for admin routes

I am looking to apply Bootstrap CSS only to routes starting with '/admin'. I have enabled lazy loading for both admin and public modules. ...

Leveraging the JavaScript NPM module through import functionality

Currently, I am utilizing the kahoot-api NPM module (GitHub, NPM) that requires JavaScript import. (edit: this is a Node.js package. At the time of writing this, I was unaware of the distinction between JS and Node.js, hence the creation of this question). ...

Turn off the Right click option on an .aspx page, but allow it on a Hyper

Can the right click be disabled on a webpage while still allowing it on hyperlinks within the same page? I am aware that I can disable right click, but if there is a way to allow it on hyperlinks, please provide the code. The main reason for disabling rig ...

Steps for including a path to a base64 encoded image

I am currently facing a challenge in embedding images into my emails where I need to encode them using an online tool. The issue I am encountering is that the email template I am using has a dynamic URL, with ${loginurl}/images as the path to my image. H ...

Creating a URL by formatting a JSON response

I am currently facing a major roadblock with formatting and processing a JSON response. Here is the sequence of steps I am following: Request data from a REST API endpoint (https://endpoint.com/api/v1/employee?id={username}) Receive the JSON response: {&q ...

Tips for setting up npm dependencies in a subfolder

Within the main directory, I have a package.json file that contains this command: "install": "cd packages/my-package && yarn". Every time I execute yarn run install, my intention is for it to enter into the specified package, set up the node modul ...

The Jquery .on Listener fails to attach a click listener to newly added elements

I'm experiencing an issue where the Jquery .on method is attaching the listener to the first button created when the page loads. However, when a new button is dynamically created by clicking on the previous one, the new button does not have any listen ...

The default date setting in AngularJS directives is malfunctioning

Is there a way to set a default date in a specific id of an HTML element? I am currently using datetimepicker in AngularJS directives, but I'm struggling to set the default date in my id. timeTracker.directive('datetimepicker', function($pa ...

Retrieving the passed argument variable and utilizing it as a key in a map

I've been working on a JavaScript project recently and I've encountered a situation where I believe my code could be significantly reduced - up to 50% - if I could access the passed arguments to a function and use them as keys. Since I'm sti ...

Recognize different HTML components when an event occurs

My application is equipped with a multitude of buttons, inputs, and other elements that trigger different events. I am looking for a way to easily differentiate between each element and the event it triggers. For instance, consider the following snippet f ...

I'm struggling to figure out the solution for this error message: "Unhandled Rejection (Type Error): Cannot read property 'filter' of undefined." Can someone please assist me with resolving this

Can you assist me? I am a beginner when it comes to javascript/React. I am currently following this tutorial https://github.com/Azure-Samples/js-e2e-client-cognitive-services and encountering the following error message: "Unhandled Rejection (TypeErro ...

The function SetInterval is invoked multiple times

I am currently working on developing a Tetris game and I have encountered a bug that affects the speed of the game. The issue arises when the function setInterval(move_tetris_part,interval_time); is called multiple times, resulting in an increased downward ...

Applying background-image in ngStyle results in an undefined value

I have been attempting to incorporate images (retrieved through an API) as the background-image of an element. However, I keep encountering the error message Cannot read property 'url' of undefined, even though the URL is actually being rendered. ...