Finding all items in an array in Cypress and validating them using JavaScript assertions

After making an API call, I have received an array response that includes the following information:

[
    {
        "IsDatalakeEnabled": true,
        "RecoveryHr": {
            "IsRecoveryHREnabled": false,
            "RecoveryHeartRateInterval": 120,
            "RecoveryHeartRateSessionTime": 300
        }
    }
]

My task is to extract each key:value pair and verify that they exist in another API call response body with the following structure:

...
"StudioAddress": null,
        "StudioProfileLanguage": {
            "LanguageName": "English",
            "LanguageCode": "en"
        },
        "IsDiversityChannel": true,
        "TotalDiversityRadios": 2,
        "IsDatalakeEnabled": false,
        "IsNetpulse": false,
        "RecoveryHeartRateInterval": 120,
        "RecoveryHeartRateSessionTime": 300,
        "IsRecoveryHREnabled": false,
        "StudioPhysicalLocationId": null,
        "StudioLocation": null,
        "IsIntroCapacityEnabled": false,
        "Status": null,
        "IsWeb": false,
        "OrangeBook": null,
        "IsFeReservationEnabled": true,
        "TimeZone": "America/New_York",
        "IsModifyMaxHr": false,
        "IsRunRowEnabled": false,
        "WeightMeasure": "LB",
...

I attempted to use cy.each(), but it treats the data as a single object:

{
    "TotalDiversityRadios": "0",
    "IsDatalakeEnabled": true
}

Any suggestions or hints on how to approach this would be greatly appreciated. Thank you!

I tried converting the response body object into an array using _.castArray(). I also experimented with Object.entries()


Update 01/14/2023 @adoff This is what my test code looks like:

validateStudioSettings() {
        // Code provided for testing purposes...
    }

While running this code in Cypress, I encountered an error: Cypress Error Console

Answer №1

To efficiently compare key/value pairs between objects, you can utilize Object.entries(obj) to generate an array of key/value pairs that can be checked against the expected object.

It's important to note that there may be nested structures within the response data.

One approach could involve flattening the response before comparing key/value pairs.

Below is a handy function that accomplishes this:

const object = {
  IsDatalakeEnabled: true,
  RecoveryHr: {
    IsRecoveryHREnabled: false,
    RecoveryHeartRateInterval: 120,
    RecoveryHeartRateSessionTime: 300,
  },
};

function keyValues(obj) {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    if (typeof value === "object") {
      const kvs = keyValues(value);
      acc = acc.concat(kvs);
    } else {
      acc.push([key, value]);
    }
    return acc;
  }, []);
}

console.log(keyValues(object))
/*
(4) [Array(2), Array(2), Array(2), Array(2)]
 0: (2) ['IsDatalakeEnabled', true]
 1: (2) ['IsRecoveryHREnabled', false]
 2: (2) ['RecoveryHeartRateInterval', 120]
 3: (2) ['RecoveryHeartRateSessionTime', 300]
 length: 4
*/

For testing purposes, consider the following sample script:

const expected = {
  ...
  "IsDatalakeEnabled": false,
  "IsNetpulse": false,
  "RecoveryHeartRateInterval": 120,
  "RecoveryHeartRateSessionTime": 300,
  ...
}

function keyValues(obj) {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    if (typeof value === "object") {
      const kvs = keyValues(value);
      acc = acc.concat(kvs);
    } else {
      acc.push([key, value]);
    }
    return acc;
  }, []);
}

cy.request(...)
  .then(response => response.json())
  .then(data => {
    const obj = data[0]
    const kvs = keyValues(obj)
    kvs.forEach([key, value] => {
      expect(expected(key)).to.eq(value)
    })
  })

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

Stop the submission process by deactivating the button until a selection is made

Is there a way to prevent the submit button from being clicked until the user has selected or typed at least one value? <form name="forma" method="POST" action="used-results.php" id="apliforma"> many textboxes and dropdown menus <a oncli ...

Error encountered due to WCF's JSON error handler triggering an exception

In the endpoint configuration, I have set up two behaviors: The first behavior is for json serialization and it closely resembles the example provided here. The important part of this behavior is as follows: public class NewtonsoftJsonBehaviorExtensio ...

Despite the presence of data, MongoDB is not returning any values

I am currently working on a code that utilizes $geoNear to find the closest transit stop to a given GPS coordinate. The issue I am facing is that the result sometimes returns undefined, even though I have confirmed that the data exists in the STOPS collect ...

Numbering the items in ng-repeat directive

I am facing a challenge with my AngularJS directive that is recursively nested within itself multiple times. The issue lies in the fact that the names of items in ng-repeat conflict with those in the outer element, causing it to malfunction. To illustrate ...

In the realm of JavaScript, what happens when a function yields yet another function while also welcoming another function as an argument?

After following a Node & Express project tutorial on YouTube, I encountered the following code snippet in an async JavaScript file: const asyncHWrapper = (fn) => { return async (req, res, next) => { try { await fn(req, res, next); } c ...

What are the steps to achieve complete test coverage for my Angular login form? Encountering an issue with reading property 'subscribe' of undefined

Recently, I made adjustments to my login component to align more closely with Angular standards. However, upon testing, I encountered errors of this kind: Cannot read property 'subscribe' of undefined After using console.log for debugging pur ...

Running multiple server and client codes on node.js simultaneously

I'm exploring the idea of establishing a network of nodes on my computer that have dual functionality as both clients and servers. Each node should be able to execute its unique server code and client code, allowing it to send requests to its individu ...

When using json_decode, the first character of string numbers will have the zero removed

When passing a phone number (which is a string) with a leading zero to the json_decode function, it ends up removing the first zero character and converting it into a float number. $phoneNumber = '09178882356'; //dynamic value echo json_decode($ ...

Store the response data in a global variable or forward it to another function in Node.js using Express JS

I'm currently working on a function that makes a post request to an API (app.post), sending a token and a URL for redirection to webpay. The challenge I'm facing is saving that token in a global variable so that it can be accessed by another func ...

Access the outcome by utilizing a for loop

Within my code, I am utilizing both a function and a loop: var songs = Musics.searchSongs(query).then(function(rs) { return rs; }); for (var i = 0; i < songs.length; i++) { console.log(songs[i]); } I am now looking for a way to execute the ...

Encountering issues while trying to generate a GitHub repository through Postman due to JSON parsing errors

When attempting to create a repository in the oops-project organization, I am using the following URL: https://api.github.com/orgs/oops-project/repos I have chosen Basic Authentication (username and password) and I am including both the name and descript ...

Transform a list of file directories into a JSON format using ReactJS

I am developing a function that can convert a list of paths into an object structure as illustrated below; this script will generate the desired output. Expected Output data = [ { "type": "folder", "name": "dir1& ...

The function(result) is triggered when an http.get request is made

Can anyone help me figure out why my function is jumping after completing the request? It seems to be skipping over .then(function(result){ }. I suspect that the issue might be related to the <a> element with an onclick attribute containing an href ...

Exploring JavaScript capabilities with Google - managing and updating object names with numbers

After importing JSON data into Google Scripts, I am able to access various objects using the code snippet below: var doc = Utilities.jsonParse(txt); For most objects, I can easily retrieve specific properties like this... var date = doc.data1.dateTime; ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

Making an Axios request with parameters

I am facing an issue where my parameter articleid is not being passed to the route /createAnswer. When I log articleData._id, it shows the correct ID (e.g., 60b4f5d8c8be1d4cb0cdd6ca) that I want to pass to the route /createAnswer. const createAnswer = () = ...

The art of simulating a service in unit tests for an AngularAMD application

I am working on an angular application using AngularAMD with require.js. I need to simulate a service as shown below: module(function ($provide) { $provide.service('ToolsService', function () { var toolsServiceMock = { som ...

"Encoding and Decoding Basic Custom Data Types in Elm: A Step-by-Step Guide

When working with Elm, I discovered that there isn't a built-in method for encoding/decoding custom types. This can present challenges when trying to send and receive custom-typed values to JavaScript. For example, how should we handle simple custom t ...

Is there a way in AngularJS to set all radio buttons to false when one is chosen as true?

When I retrieve true/false string values from the database, I am unable to alter the data. The example I provided is simply a representation of the string values true or false that I receive from the database. My goal is to have a single radio button disp ...

Custom CSS for the Google Maps Circle Object

Currently, I am utilizing the Google Maps Javascript API v3 Circle object to display circles on the map. I am interested in customizing the CSS of this circle by incorporating some CSS animations. Although I am aware that custom overlays can be used for t ...