Cypress 7: Dealing with the onRequest Problem in the cy.intercept Function

We encountered a situation where we needed to assert that a spinner was displayed during a request using the following code:

The code functioned properly in Cypress 6.4.0

cy.intercept({
  url: '*',
  onRequest: () => {
    cy.get('[data-testid=spinner-loading-indicator]')
    .should('exist')
  }, 
});

However, in Cypress 7.5.0, onRequest is no longer accepted. The closest alternative we found was:

cy.intercept('*', (req) => {
  req.on('before:response', (res) => {
     cy.get('[data-testid=spinner-loading-indicator]').should('exist')
  })
})

This solution resulted in an error due to Cypress not allowing promises in this context (cy.get() returning a promise)

Has anyone encountered a similar issue, and if so, how was it resolved?

Answer №1

If you want to make a change,

cy.get('[data-testid=spinner-loading-indicator]').should('exist')

You can switch it to this,

expect(Cypress.$('[data-testid=spinner-loading-indicator]')).to.exist

The main difference is that the second (jQuery) test does not retry - it's unclear if that will pose any issues without knowing the sequence of events in your question.


Testing the loading indicator within the intercept seems like testing multiple things at once, which might cause flakiness due to timing issues, especially in a CI environment.

Is there a specific reason why this sequence is not suitable?

cy.intercept('*').as('requested')

// trigger events
cy.visit('some-url')       // if initiated on load
// or
cy.get('button').click()   // if user-initiated

cy.wait('@requested')      
cy.get('[data-testid=spinner-loading-indicator]').should('exist')

Regarding events, the execution of the routeHandler (req) => {...} determines the onRequest event, but you are still unable to execute commands inside it.

Essentially, this is equivalent to the syntax using onRequest,

cy.intercept('*', (req) => {
  cy.get('[data-testid=spinner-loading-indicator]')        // throws an error 
})

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

Following the upgrade of Angular, the webpack module source-map-loader is encountering an error: "this.getOptions is not a function"

Currently in the process of constructing my angular project using webpack alongside source-map-loader to extract source maps, like this: module.exports = { // ... module: { rules: [ { test: /\.js$/, enforce: "pre&quo ...

The accuracy of getBoundingClientRect in calculating the width of table cells (td)

Currently, I am tackling a feature that necessitates me to specify the CSS width in pixels for each td element of a table upon clicking a button. My approach involves using getBoundingClientRect to compute the td width and retrieving the value in pixels (e ...

Error when handling JSONP: Unexpected token colon in SyntaxError

Encountering a similar issue to the ones discussed in this JSON Uncaught SyntaxError thread and this JSONP Unexpected Token error thread. I attempted to fetch Divvy data through a JSONP call to avoid using a server for my simple front-end application. $. ...

What are the steps to implement the jQuery slide menu effect on a website?

When visiting the website , you may notice a symbol positioned in the top left corner of the site. By clicking on this symbol, a sleek div will slide out. How can this type of animation be achieved through javascript or jquery? ...

How to eliminate undefined values from a dropdown selection in AngularJS

Blockquote When choosing a material from the column, the first option is showing as undefined. How can I remove undefined from the drop-down list? What changes need to be made in the HTML/JSON data for this to work properly? Blockquote var app = ang ...

Error message: Suitescript encountered an unexpected issue - TypeError: The function this.handleChange is not defined

For the past year, I have been immersed in Suitescript development. In my current project, I have a client script that triggers on Save for a Journal Entry. However, upon trying to save, I encounter an error message that reads "TypeError this.handleChang ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...

How come my $scope variables are not resetting when attempting to refresh the data?

I just started working with Angular and encountered an issue while trying to implement a reload button. My webpage displays a table with data pulled from a Parse database. The table can be modified using various buttons, and after making changes, I want to ...

Editing XHTML on the fly

Is there a tool available for non-technical individuals to edit hard-coded content in XHTML? I am interested in a solution similar to the integration of Pagelime with jEditable. Currently, my website is static and I am seeking a way for one person to log ...

Encountering a Cypress testing issue linked to webpack. Feeling unsure about the next steps to address it

https://i.sstatic.net/z6bmW.png I encountered an error while attempting to run a test file that I created. The default tests run smoothly, but the error only occurs with the file I created. import {cypress as cy} from "cypress" describe('T ...

Is it possible to generate an array of objects, where each object includes an observable retrieved through forkJoin?

let food = { id: 1, isTasty: false } Imagine I have a custom function that takes the ID of a food item and returns an observable which resolves to a boolean indicating whether the food is tasty or not. I wish to loop through an array of food items an ...

Breaking down a large array in Node.js to initiate multiple API calls

I am currently faced with a challenge where I have a CSV file containing 21k records, with each record being a single alphanumeric word. I need to process these records by sending them to an API in JSON key-value pair format. The API can only accept 500 el ...

Importing .js files from the static folder in Nuxt.js: a step-by-step guide

I'm in the process of transitioning my website, which is currently built using html/css/js, to Nuxt.js so that I can automatically update it from an API. To maintain the same website structure, I have broken down my code into components and imported ...

JavaScript date formatting without using jQuery

Looking for help to apply a date mask (dd/mm/yyyy) on an ASP.net textbox. I have tried several JavaScript solutions found through Google search, but none seem to work seamlessly, especially with backspacing. Any suggestions for a reliable script would be ...

Error: The function window.intlTelInput is not recognized within the ReactJS framework

I am currently learning ReactJS and encountering an issue when using jQuery with React JS for intlTelInput. I have installed npm jQuery and imported all the necessary code. Additionally, I have included all the required CSS and jQuery links in my index.htm ...

Running an ESNext file from the terminal: A step-by-step guide

Recently, I delved into the world of TypeScript and developed an SDK. Here's a snippet from my .tsconfig file that outlines some of the settings: { "compilerOptions": { "moduleResolution": "node", "experimentalDecorators": true, "module ...

jquery technique for toggling a single button

My goal is to use jQuery to toggle a button rather than the typical paragraph toggling. I want the button to appear and disappear when clicked, while also increasing the "score" upon each click and decreasing it when the button reappears. Can anyone guide ...

Is there a way to make the submit button navigate to the next tab, updating both the URL and the tab's content as well?

I am encountering an issue with my tabs for Step1 and Step2. After pressing the submit button in Step1, the URL updates but the component remains on tab1. How can I resolve this so that the user is directed to the Step2 tab once they click the submit butto ...

Ways to transfer a v-model from the parent component to a template

I'm currently in the process of designing the user interface for a search page and I want to utilize components to help with code reusability. However, I am facing a challenge in figuring out how to pass the model of the page to the search component. ...

Grid layout with card tiles similar to Google Plus

I'm looking to develop a scrolling grid with card tiles similar to Google Plus that has three columns. I am currently using Material UI, but I can't seem to find the right functionality for this. I have experimented with the standard Material UI ...