What is the process for obtaining the cypress interception fixture twice but in two distinct formats?

Hi there, I'm new to Cypress and facing a challenge that I hope you can help me with.

In my test file, I have the following code:

cy.SetupClassificationsStubFixture(1);

This code refers to a custom command that I've created:

Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {

cy.fixture('ClassificationsStub.json').then(classificationsStub => {
    const slicedClassifications = classificationsStub.slice(0, amount)
    cy.intercept('GET', '**/api/classifications', slicedClassifications)
}).as('classifications')

cy.fixture('ClassificationsStub.json').then(classificationsStub => {
    const slicedClassifications = classificationsStub.slice(0, amount)
    cy.intercept('GET', '**/api/classifications/*', slicedClassifications)
}).as('classifications')
});

With this code, I am intercepting 2 API requests:

  1. ** /api/classifications
  2. ** /api/classifications/ *

The issue is that both responses are returning with brackets '[]'. I tried creating a second fixture file without brackets, but the slice function did not work as expected.

So, what I need is for the second intercepted response to be like this:

{
    "id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
    "name": "CypressTest",
    "userRole": "Editor",
    "childClassifications": []
}

But currently, it is returning like this:

[
{
    "id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
    "name": "CypressTest",
    "userRole": "Editor",
    "childClassifications": []
}
]

How can I get rid of the brackets in the array? Thank you!

UPDATE: I am attempting the following solution now:

Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {

cy.fixture('ClassificationsStub.json').then(classificationsStub => {
    const slicedClassifications = classificationsStub.slice(0, amount)
    cy.intercept('GET', '**/api/classifications', slicedClassifications)
}).as('classifications')

cy.fixture('ClassificationsStub.json').then(classificationsStub => {
    const slicedClassifications = classificationsStub.slice(0, amount)
    const arr2 = slicedClassifications
    const obj5 = Object.fromEntries(arr2)
    
   
    cy.intercept('GET', '**/api/classifications/*', obj5)
}).as('classification')
});

However, this is resulting in an empty .json file. The response is not just '{}'

Answer №1

There appears to be a few brackets misplaced within the code block.

I would suggest using distinct alias names to prevent any unexpected behavior when calling cy.wait('@classifications').

Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {

  cy.fixture('ClassificationsStub.json').then(classificationsStub => {

    const slicedClassifications = classificationsStub.slice(0, amount);
    cy.intercept('GET', '**/api/classifications', slicedClassifications)
      .as('classifications');

    const firstClassification = slicedClassifications[0];  // retrieve only the first item
    cy.intercept('GET', '**/api/classifications/*', firstClassification)
      .as('firstClassification');

  });
});

Answer №2

If your data is structured like this:

var userData = [{
    "id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
    "name": "CypressTest",
    "userRole": "Editor",
    "childClassifications": []
}]

To access the data with curly braces, you can use userData[0].

{
    "id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
    "name": "CypressTest",
    "userRole": "Editor",
    "childClassifications": []
}

Here is a screenshot of how it looks on the console:

https://i.stack.imgur.com/OzUzB.png

Answer №3

Successfully resolved using:

Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {

cy.fixture('ClassificationsStub.json').then(classificationsStub => {
    const slicedClassifications = classificationsStub.slice(0, amount)
    cy.intercept('GET', '**/api/classifications', slicedClassifications)
}).as('classifications')


cy.fixture('ClassificationsStub.json').then(classificationsStub => {
   
    cy.intercept('GET', '**/api/classifications/*', (req) => {
        const slicedClassifications = classificationsStub.slice(0, amount)
        var selectedClassification = req.url.replace(new RegExp('.*api/classifications/'), '');
        let foundClassification = FindChildClassification(selectedClassification, slicedClassifications);

        //If not found return first always
        req.reply({
                    statusCode: 200,
            body: foundClassification ?? slicedClassifications[0]
                })
    })
}).as('classification')

Additionally,

export function FindChildClassification(id, classificationArray) {
for (let i = 0; classificationArray.length - 1 >= i; i++) {
    if (classificationArray[i].id == id) {
        return classificationArray[i];
    } else {
        if (classificationArray[i].childClassifications.length > 0) {
            let childClassification = FindChildClassification(id, classificationArray[i].childClassifications);
            if (childClassification != null) { return childClassification }
        }
    }
}

return null;

}

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

Teach me how to utilize Import / require() in Static Folder

I've been attempting this task for a while, but I'm unsure how to incorporate import or require into the express static folder. When I try to use it, I receive an error stating "require not defined" which makes sense since these are not supported ...

The second function in Vue.js was unable to initialize the data field within data() due to a missing call for assistance

I have very little experience working with vue js. There are two functions that I am using: loadComponentsOfUser() and loadUserId(). The loadComponentsOfUser() function depends on the userID field being loaded by the loadUserId() function. data() { retu ...

Tips on enlarging the header size in ion-action-sheet within the VueJS framework of Ionic

Recently I started using Vue along with the ionic framework. This is a snippet of code from my application: <ion-action-sheet :is-open="isActionSheetOpen" header="Choose Payment" mode="ios" :buttons="buttons&qu ...

Getting the value from a function that validates against multiple date ranges within an array in PHP

Trying to determine if today's date is within certain date ranges stored in an array using a custom function. I'm looking for a way to extract the $location value returned by the checkRange function. function promoDates(){ $current = strtoti ...

display the values of the array object within the ajax success callback

When I receive the result, it looks like this But now I want to display that content inside a dropdown box with option values. How can we accomplish that? My current approach is as follows: var data = data.user_contacts var formoption = ""; ...

"Utilizing jQuery's bind method with IE 7 compatibility and the use of

One of the scripts I'm working with is a treeview script, and a portion of it appears like this: root.find("." + classControl).each(function () { $(this).bind('click', function () { if ($(this).text() == "-") { $(thi ...

Can you explain the distinction between using this.function and making a function call in React?

I'm new to React and recently came across some code in a project that confused me. Could someone please clarify the distinction between this.function and the following function call used in a React event handling prop? <button onClick={this.clickH ...

What is the best way to set the sidebar height to 100% in Material-UI?

Trying to learn MUI and encountered a problem. I want the sidebar to cover the full height, I tried 100vh but it stops increasing when the table extends. Using 100% only covers the end of the list. Is there another way to solve this, or is it fine becaus ...

What's the Deal with Angular's Watch Service for Monitoring Data Changes?

I have a service called SharedData which is defined like this: appServices.service('SharedData', function() { var data = {}; function setContacts(contacts) { data.contacts = contacts; }; function getContacts() { ...

showing information on webpage 2 received via query parameters from webpage 1

Hello, I am trying to input text into a textarea and then send the data through a query string to another webpage. My goal is to display the data on the second webpage. I have written the following code, but it doesn't seem to be working. I've ch ...

Is it possible to loop through a subset of a collection using *ngFor?

Is it possible to iterate through a specific range of elements in a collection using *ngFor? For instance, I have a group of checkboxes with their form control name and label specified as follows: [{id: 'c1', label: 'C1'}, ...] Assum ...

Shift all content to the right when viewing on mobile devices

I'm looking to create space for a menu on the left side, similar to the one on Mashable's mobile view. How can I move all the content to the right? Feel free to resize the window and compare with . Thank you. Best regards, Marius ...

Using JavaScript to display a selection of objects from an array: showcasing x out of x items

What is the most efficient method for sorting or querying an array of objects using JavaScript? For example, how can I retrieve only the first two objects, followed by the next two, or obtain 5 objects starting from the 5th position? Which specific functi ...

Angular code is failing to send a signal to the server following a $http.post request

I've been using angular for about a week now and I've been struggling to solve this issue. I have a service that wraps around $http because multiple controllers make calls to the same URL. On one particular page, there is a lot of server-side bus ...

The CSS selector functions as expected when used in a web browser, however, it

While conducting test automation using Selenium, I typically rely on css selectors to find elements. However, I recently came across a peculiar issue. I observed that in certain cases, the css selector works perfectly when tested in the browser console. Fo ...

In Pure JavaScript, an HTML element is added every time the click event is triggered

Hey everyone, I'm facing a small issue and I could use some help fixing it. I need to implement an onclick event that adds HTML code every time it's clicked. I am hesitant to use innerHTML due to its potential risks. Here is the code snippet: bu ...

Displaying an image prior to the component rendering in Vue.js

In my Vue application, I have a list of events that are displayed individually. When I visit the page of a selected event, an error message appears in my console: GET http://localhost:1337/undefined 404 (Not Found). However, the image still loads correctly ...

Is it possible to include a submenu within a md-tooltip?

I have set up an md-tooltip for a sidebar, but I would like to enhance it by enabling a submenu option. For instance, if there is a Contacts submenu under the Profile menu, I want to be able to access Contacts when hovering over the Menu Icon. The tooltip ...

Leveraging Ajax with PlayFramework Results

As stated in the PlayFramework Document 2.0 and PlayFramework Document 2.1, it is known that Play can return various responses such as: Ok() badRequest() created() status() forbidden() internalServerError() TODO However, when trying to send a response wi ...

"Running experiments with Google Ads and Google Analytics scripts results in a blank page being displayed

Currently, I am working on a plain HTML file and conducting tests to ensure that the Google Ads and Analytics scripts are functioning correctly before implementing them on other pages. A colleague who has an AdSense account provided me with the script code ...