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

Searching in Vue based on the selected option is only possible by the selected criteria and not by id, regardless of the

#1 Even if chosen, cannot search by id. The 'name' condition in the loop works well but I am unable to correctly search by id (returns nothing). #2 When selecting an option from the dropdown menu, it only displays until I start typing. I would l ...

Modifying the DOM within a getJSON callback

My current challenge involves fetching data from the YouTube API and displaying it on my website. However, I am facing an issue where the DOM changes made inside the getJSON's callback function are not reflecting on the webpage. Even though I can see ...

Accessing the JSON file from the Google Maps Places API using either JavaScript or PHP

In the midst of developing an application, I am working on fetching a list of places near a specific latitude and longitude. After obtaining an API key, inputting it into the browser URL successfully retrieves a JSON file containing the desired places dat ...

When attempting to import Three.js canvas on Github Pages, a 404 error is received

While attempting to host my webpage with a three.js background, I encountered an issue where everything loads properly when hosted locally, but nothing loads when pushed to GitHub pages - only the HTML is visible. I am utilizing Vite to package my code an ...

Solution for fixing the error: MongooseError [OverwriteModelError]: It is not possible to overwrite the `User` model after it has been compiled in

I am new to working with the MERN stack and currently attempting to create an exercise tracker app following a tutorial on YouTube. However, I am encountering the Mongoose: OverwriteModelError when running the server and cannot seem to identify where I am ...

Is my JSON data causing the error of invalid React child components?

Although this question has been asked multiple times on Stack Overflow, the solutions provided have not worked for me. My main goal is to retrieve notifications from a JSON file located here: I suspect that my JSON file may be poorly structured, especial ...

Tips on handling a Vue computed property

I am struggling to dispatch an object that is created within a computed property in vue.js. Being fairly new to this framework, I can't seem to make it work. My goal is to dispatch the object named "updateObject" to the vuex-store. I have tried using ...

Is there a way to verify file types using Vuelidate?

Is there a way to validate file types like png, jpg, and jpeg using Vue.js's Vuelidate library? ...

The backface remains visible despite being designated as "hidden"

I have successfully created a "flip card" in CSS3, where the card flips downward to reveal the other side when a user hovers over it. I have ensured that the back face is not visible by setting backface-visibility to hidden. However, despite my efforts, th ...

Using JavaScript regex to eliminate content enclosed in parentheses, brackets, and Cyrillic characters

Is there a way to transform (Test 1 / Test 2) [Test 3] Отдел / Here is title - subtitle (by Author) - 1234 (5678-9999), descriptions (best), more descriptions into Here is title - subtitle (1234) (descriptions) using a combination of JavaScript an ...

Created JSON object providing the number as a string value

I am currently facing an issue with a Vue method where it generates a JSON object from user input values before making an axios put request. The problem I'm encountering is that the JSON object generated converts numbers into strings, causing issues w ...

Tips for ensuring synchronous state changes in React

I am working on a currency calculator using react.js I am fetching the latest exchange rates and storing them in state using the getRates function: getRates(currencyShortcut){ fetch('https://api.fixer.io/latest?base='+currencyShortcut) ...

Inability to update Vue.js component data even after a successful GET request

I am encountering an issue with a component that initially contains a default object, and then fetches a populated object via a GET request upon creation. Despite successfully updating this.profile within the method, the changes do not seem to propagate ...

Button for Toggling Audio Play and Pause

Is it possible to create an SVG image that changes color slightly when hovered over, and when clicked toggles to another SVG image that can be switched back to the original by clicking again with the same hover effect? Additionally, when clicked, it should ...

Issue with AngularJS form not binding to $http request

<form novalidate class="form-horizontal"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="text-capitalize"> </ ...

Make sure the "Treat labels as text" option is set to true when creating a chart in a Google spreadsheet using a script

I am currently working on a script using Google Spreadsheet Apps Script interface and I need to set the marker for 'Treat labels as text' to true. Despite searching through App Script documentation, I couldn't find any specific mention of t ...

Generating a single JSON record in React Native

Need help displaying a single JSON record from an API request on the screen. const [user, setUser] = useState(); const getUserData = async () => { // {headers: {Authorization: "Basic " + base64.encode(username + ":" + passwor ...

Keep an eye on the syncing progress of pouchdb replication

What is the best way to alert the user if there is a loss of Internet connection or if the server goes offline, causing live sync to stop? var localdb = new PouchDB('localdb'); var remotedb = new PouchDB('http://localhost:5984/xyz&a ...

I currently have a form within a div that is part of a loop to showcase saved data. My objective is to identify any changes made in the form fields so I can detect them effectively

This code is located inside a loop <div class="card card-fluid"> @php $counterId++; $formId = 'startLog'.$counterId; @endphp {!! Form::open(['id'=>$formId,'class'=>'ajax-form','method& ...

I developed an RPG game with an interactive element using jQuery. One of the biggest challenges I'm facing is the random selection process for determining which hero will be targeted by the enemy bots during battles

Hello, this marks my debut on stack overflow with a question. I've created a game inspired by old school RPGs where players choose from three heroes based on the Marvel universe to battle one of three enemies. The problem I'm facing is that even ...