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

Tips for developing screen reader-friendly AJAX areas and managing updates to the DOM?

My interactive user process operates in the following manner: Users encounter a dropdown menu featuring a selection of cities. Upon picking a city, an AJAX request retrieves all buildings within that city and inserts them into a designated div (the AJAX ...

Unable to run the JSON.parse() function while using the 1.10.2 version of jquery.min.js

Has anyone else encountered a situation where using JSON.parse() to parse the PHP array return only works when applying 1.3.2/jquery.min.js and not 1.10.2/jquery.min.js? If so, what solution did you find? PHP array return $returnArray['vercode' ...

Can JavaScript be used to retrieve time information from a central location?

In the process of developing a PhoneGap application, I am restricted to using only HTML, CSS, and JavaScript. I am seeking guidance on how to retrieve time information from a centralized server using strictly JavaScript. Is it possible to achieve this by ...

Exploring variations in error handling for JavaScript promises in Node.js depending on whether the error is synchronous or asynchronous

Exploring the nuances of promise error handling for thrown errors and exceptions in the promise executor, particularly in comparison to reject, within a node.js context. Differences in handling between reject and throw/exceptions are evident. Some source ...

When clicking on the dress in the masque, how do I change the attire so that it is instantly applied to the masque?

$("#tail").kendoFlatColorPicker({ preview: false, value: "#000", change: select }); $("#head").kendoFlatColorPicker({ preview: false, value: "#e15613", change: select }); I implemented the color ...

Assurance-driven number tally

I'm diving into JavaScript and recently started exploring promises. I've put together a code snippet that logs the value passed to the promise function as a parameter after the setTimeout function is triggered. Now, I'm wondering if there&ap ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Using MEAN.JS to Define Query Parameters for Mongo from the Client Controller

I am currently developing an application using the MEAN stack - MongoDB, Angular, Express, and Node.js. To kickstart my project, I utilized the MEAN.JS generator to set up the initial structure of my application. The articles module within my application ...

Bring in camera from gltf

Can someone provide guidance on utilizing a camera from gltf within three-js? I am currently implementing the gltf loader as demonstrated in this example. ...

Creating a JavaScript function to selectively blur elements while leaving one in focus

My goal is to blur all elements on a webpage except for the p#this tag using vanilla JavaScript. I am determined to learn the intricacies of JavaScript, so I'm not looking for solutions involving jQuery or CSS. I came across a potential solution on t ...

The concept of "Object Reference Pattern" in the world

Currently, I am working with a single object: var callback = { onValueChange: function () { }, onTabPressed: function () { }, onFocus: function () { } }; In my webpage, I have various editors such as textEditor and numericEditor, and I bind t ...

Transforming a function into its string representation | 'function(){...}'

func=function() {foo=true} alert(JSON.stringify(func)); alerts "undefined" obj={foo: true} alert (JSON.stringify(obj)); alerts: "{foo: true}" Have you ever wondered why JSON.stringify() doesn't work for a "function object"? It seems that when tryi ...

Displaying Props Information in a Modal Window using React

Currently venturing into the realm of React JS, where I am in the process of developing a sample eCommerce application for real-time use. However, I have hit a roadblock. In my Products List, there is a Buy button for each product. When clicking on this b ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Dynamic reloading of a div with form data using jQuery's AJAX functionality

I am currently developing an online visitor chat software using PHP and MySQL. My goal is to load the page when the submit button is clicked. Submit Button ID: send Visitor ID: vid Chat ID: cid Below is the snippet of code for an Ajax request that I hav ...

Updating a single .jshintrc option for a folder

My project has a .jshintrc file at the root, containing the following settings: { "node": true, "smarttabs": true, "undef": true, "unused": true } While these settings work well for node-related code in my project, they are not suitable for brows ...

Experiencing trouble with calculating the total value of an array of objects due to NaN errors

I've been working on developing this web application in VUE.js, but I'm facing an issue with a specific function where I am attempting to sum the values of each object within an array. This is resulting in a NaN (Not a Number) error. Let's t ...

best way to sort through an array using jquery in javascript

Is there a way to filter a jQuery array like in SQL server with "Like % %"? var array=[ {"job_category":"hello sir","job_location":"hello dear"}, {"job_category":"dear kumar ","job_location":"sir"}, {"job_category":"testts ssss ss","job_location":"hello t ...

The issue persists with the Javascript AJAX POST Method as it fails to transmit values to the designated

I have been using Javascript AJAX to make a request to a php page and receive the output from that page. Interestingly, when I use the GET method in my AJAX call, everything works as expected. However, the issue arises when I try to use the POST method. B ...

405 status code returned for CORS request

Hello everyone, I need assistance with my CORS issue. I am trying to make an API request from another domain and encountering an error with the following code: var headers = { host: host, path: url + instance + '?action=reset', ...