What is the correct way to set up Cypress intercepts within a beforeEach function?

As a newcomer to Cypress, I find some aspects of it challenging despite its apparent simplicity. I am facing a specific issue:

  const componentsRouteMatcher = {
    pathname: '/component-management/api/components',
    query: {
      size: '5',
      page: '0',
      property: 'name',
      direction: 'asc',
      activated: 'true',
      organisationId: '33'
    }
  };

    beforeEach(() => {
   

    cy.interceptStaticDataCalls(); // a custom command with interceptor registrations

    cy.intercept(componentsRouteMatcher, {fixture: 'components/first-5.json'}).as('first5');

    const composSecond5Route = Object.assign({}, componentsRouteMatcher, {query: {page: '1'}});
    cy.intercept(composSecond5Route, {fixture: 'components/second-5.json'}).as('second5');

    const composFirst50Route = Object.assign({}, componentsRouteMatcher, {query: {size: '50'}});
    cy.intercept(composFirst50Route, {fixture: 'components/first-50.json'}).as('first50');

    const composFirst20Route = Object.assign({}, componentsRouteMatcher, {query: {size: '20'}});
    cy.intercept(composFirst20Route, {fixture: 'components/first-20.json'}).as('first20');


    cy.intercept('/component-management/api/functional-areas', {fixture: 'functional-areas/functional-areas.json'}).as('fa');

  });

 it('should display all components based on a default filter', () => {
    cy.visit("/");
    cy.wait(['@first20', '@fa'], {timeout: 5000});
});

The problem lies in the last interceptor - although it loads a large JSON fixture file, it doesn't intercept properly. Surprisingly, it appears in Cypress's list of available routes. When I move this particular interceptor to the beginning of the beforeEach block, it works. It seems there might be an asynchronous process causing issues which is not very intuitive. Is there a reliable way to set up all these interceptors without having to guess their order?

I appreciate your help!

UPDATE:

// standard set of initializations required for all tests
Cypress.Commands.add('interceptStaticDataCalls', () => {
  cy.intercept('/component-management/api/jira/project', { fixture: 'projects.json'});
  cy.intercept('/component-management/api/appclientrelationships/apps', { fixture: 'apps.json'});
  cy.intercept('/component-management/api/appclientrelationships/clients', { fixture: 'clients.json'});
  cy.intercept('/component-management/api/appclientrelationships', { fixture: 'appClientRelationships.json'});
  cy.intercept('/component-management/api/usergroups', { fixture: 'usergroups.json'});
  cy.intercept('/component-management/api/organisations', { fixture: 'organisations.json'});
  cy.intercept('/component-management/api/configs', { fixture: 'configs.json'});
  //pathname used here to avoid intercepting current user request
  cy.intercept({pathname: '/component-management/api/users'}, { fixture: 'users.json'});
})

Answer №1

After delving into the depths of Cypress documentation, I came to understand that the majority of operations in Cypress are asynchronous, especially when it comes to registering request interceptors (which follow an event-driven model). In order to ensure that I properly "visit" the home page only after all interceptors have been registered, I decided to consolidate everything into an async function. This involved annotating all async processes with await keywords before visiting the "/" endpoint. Below is an example illustrating this approach:

async function initializeTests() {

  cy.registerStaticDataIntercepts();

  await cy.intercept(componentsRouteMatcher, {fixture: 'components/first-5.json'}).as('first5');

  const second5Route = Object.assign({}, componentsRouteMatcher, {query: {page: '1'}});
  await cy.intercept(second5Route, {fixture: 'components/second-5.json'}).as('second5');

  const first50Route = Object.assign({}, componentsRouteMatcher, {query: {size: '50'}});
  await cy.intercept(first50Route, {fixture: 'components/first-50.json'}).as('first50');

  const first20Route = Object.assign({}, componentsRouteMatcher, {query: {size: '20'}});
  await cy.intercept(first20Route, {fixture: 'components/first-20.json'}).as('first20');

  await cy.intercept('/component-management/api/functional-areas', {fixture: 'functional-areas/functional-areas.json'}).as('fa');
}


.....

  beforeEach( () => {
    initializeTests().then( () => {
      console.log('Initialization complete!');
      cy.visit("/");
    })
  });

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

Execute a bash script from a local URL using fetch

I'm curious about converting a curl command into a bash script with input variables using fetch. It works perfectly in the console: curl -s http://localhost:3001/ident.sh | bash /dev/stdin x627306090abab3a6e1400e9345bc60c78a8bef57 2 10194897676576 ...

useEffect does not trigger a rerender on the primary parent component

I am facing an issue where the main parent component does not re-render when I change the state 'click button' in another component while using useEffect. Oddly enough, the main <App /> component only re-renders properly when I reload the p ...

What is the best way to display a Vuex state based on a function being activated?

I have noticed similar questions on this topic but couldn't find a solution, so I decided to create my own. Here's the issue: I have an array named "allCountries" in the state, initially filled with 250 country objects. I am successfully render ...

What could be the reason for my electron application consistently displaying false results when using Google Authenticator, despite entering the correct token?

Within this snippet of code, I am initiating a request to the main process to create a QR code using speakeasy and qrcode. document.addEventListener('DOMContentLoaded', async function() { const data = await ipcRenderer.invoke('generate-q ...

Conceal form upon submission with jQuery

Is it possible to have a html form inside a table and then hide it once the form is submitted? The Form: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <tr> <td colspan="3"> <h ...

Ways to update a nested object by utilizing the setState method

I have a situation where I need to modify the key/value pairs of an object in my state. Specifically, I need to add a key/value pair to the object with an ID of 13. Please refer to the attached photo for reference. Although I know how to use setState, I ...

Can a FilePicker be Cleared Automatically through Code?

Currently, I am implementing an‘<input type="file" . . .’ to select files individually and then attach them to a table located right under the file picker. This functionality is quite similar to using the attachment button on a SharePoint form’s r ...

How can I access the feed of a single user using the Facebook API

I have yet to experience working with Facebook APIs, but I am interested in developing a basic app that will display posts from a specific Facebook user. I would prefer not to enable login for multiple users, just keep it simple. My goal is to create an a ...

Using jQuery Mobile alongside two distinct versions of jQuery

My current task involves inserting both jQuery and custom JavaScript into the DOM of an existing page. The jQuery is inserted right before my script, where I utilize window['my$'] = jQuery.noConflict(true);. This approach worked smoothly after ...

As soon as a key is pressed in tinyMCE, the tracking continues until reaching the conclusion of the initial <

I am attempting to capture, in real-time, the user input in the .content textarea and paste it into the .intro. I have tried the following code without success: //This code is specifically for tinymce, as I am using tinyMCE as a rich text editor for textb ...

Modify and improve promise and promise.all using the async/await feature of ES2017

I have successfully implemented a photo upload handler, but I am now exploring how to integrate async await into my code. Below is the working version of my code using promises: onChangePhotos = (e) => { e.preventDefault() let files = e.target ...

Having trouble bringing in icons from the @mui/icons-material library

An error occurs when attempting to run the code. wait - compiling... error - ../../../../../node_modules/@mui/icons-material/esm/utils/createSvgIcon.js:1:0 Module not found: Can't resolve '@mui/material/utils' null Note: @mui/material pack ...

Tips on how to showcase various information in distinct tabs using VueJS

I am currently working on a website project utilizing the VueJS framework and Vuetify template. My goal is to showcase different content under separate tabs, however, I'm encountering an issue where the same content is being displayed in all three tab ...

Updating state in Vue by utilizing an array of item values

Hello everyone In a simple application, I am attempting to visualize the insertion sort algorithm using Vue. I have successfully written a function that sorts a list of items and returns an array showing each step of the sorting process. The final array i ...

Modify a dropdown menu selection and process it using ajax technology

My Simple HTML Form: <select id="single"> <option>Option 1</option> <option>Option 2</option> </select> <input value="load()" id="test" type="submit" /> <div id="result"></div> Javascript Co ...

Problem with sending data using $.ajax

I stumbled upon a strange issue. In one of my php pages, I have the following simple code snippet: echo $_POST["donaldduck"]; Additionally, there is a script included which makes a $.ajax call to this php page. $.ajax({ url: "http://provawhis ...

Steps for generating a unique division element for every javascript response

How can I dynamically create a new div for each response in JavaScript? The message is in JSON format containing all the messages sent and received. This is my JavaScript code: $.get("MessageServlet", function (responseJson) { $.each(responseJ ...

Converting a decimal Unicode to a string in Javascript/Node: a beginner's guide

In my database, I have Arabic sentences that contain decimal unicodes for quotation marks and other elements. For example, here is a sample text: "كريم نجار: تداعيات &#8220;كورونا&#8221; ستغير مستقبل سوق السي ...

Is there a problem with textbox support for multi-line strings?

I'm having trouble getting a textbox to display multiple lines of text. For instance, when I copy three lines of text from Microsoft Word and paste it into the textbox, only the first line appears. The other two lines are not showing up, and I'm ...

Create a router link in Vue using the command "Vue

I have a Vue application that displays videos. I am looking to automatically generate a random router link every time I click on: <router-link to="/video/this_value_to_be_random">Random video</router-link> Within the component: <vue-vide ...