
Recently i came across a scenario where my API response returns an array with process Id and it’s Status and My test has to validate that the status for all the items in the array is same and if not, throw assertion error and fail the test.
Below is the sample response i get from an API as array.
We can use lodash library to perform operations on array. Cypress comes with lodash library integrated by default.
we can access lodash functions in Cypress like below
Cypress._.<function>
For our use case, where we need to validate the all the elements contain the property and value we are looking for, We can use .every() function of lodash
Syntax will be like below.
Cypress._.every(arrayWeWantToValidate, expectedPropertyWithValue)
As we can see .every() function accepts two parameters, 1st one is the array/collection and 2nd parameter is the expected property and its value that we expect to present in all the elements in the array.
Let’s write our Cypress test for this
Let’s break down the code.
We are assigning the array to a variable, this array can usually come from as API response or from Web page.
let testArry = [
{
processId: 1,
status: 1,
startDate: "2023-06-09T14:38:40.4404499",
endDate: null,
},
{
processId: 4,
status: 2,
startDate: "2023-06-09T14:31:40.9584041",
endDate: "2023-06-09T14:31:40.9655563",
},
{
processId: 6,
status: 2,
startDate: "2023-06-09T14:36:02.3850904",
endDate: "2023-06-09T14:36:06.4816924",
}
];
Once we have the array we can then use the every() function to validate with expected value
Cypress._.every(testArry, ["status", 2])
The above code will return the boolean value based on the expected value we pass. In the above case, what we are expecting is all the elements in the testArry to contain property “status” with value 2.
If any one element in the collection has different value in status then the boolean value that above code returns is false.
We can now assert the value returned by every() function using .expect() or .should()
With expect() we can write code like below
expect(Cypress._.every(testArry, ["status", 2])).to.deep.equal(true);
We also can wrap the return value from every() function and later we can assert using .should() like below
//wrap it for later usage or assertion
cy.wrap(Cypress._.every(testArry, ["status", 2])).as("status");
//assert by using get function to get the wrapped alias
cy.get("@status").should("equal", true);
Note: expect() doesn’t retry and should() will retry, so use the type of assertion based on your requirement.
Easy isn’t it!! Hope this example helped you. Please leave a comment and Clap 👏 if you liked this example

Leave a comment