Can i use If statements to verify an array contains the correct data based on the first object inside that array?


Im trying to create a test where i verify that the data within an array is correct using an If statement. Below is the json im testing against and i want to be able to create a test so check that if there is a specific ID returned, then the following data in that array is correct if thats even possible?

        "id": "04e7e4ac",
        "title": "Simple rules & mistakes to avoid",
        "slug": "simple-rules-and-mistakes-to-avoid/dp/04e7e4ac",
        "productType": "e-learning-module",
        "isConfigurable": false,
        "shortDescription": null,
        "defaultVariant": {
            "sku": "78e12e11",
            "price": "£4.99",
            "originalPrice": "£4.99"
        "images": [
                "type": "main",
                "baseUrl": "",
                "path": "/sylius/assets/images/8f/3c/9f99ea632a02773d237574b5962e.jpg"
        "categories": []

So i want to check that if the ID equals “04e7e4ac” then the rest of the json has the correct values, i.e “title”: “Simple rules & mistakes to avoid”,

I have tried the below but its returning a pass regardless of the data im inputting

pm.test("Data for ID is correct", () => {
let jsonData = pm.response.json()
if ( === "04e7e4ac") {
        pm.expect(jsonData.title).to.eql("Simple rules & mistakes to avoid")

The test is passing because the IF statement is failing, therefore none of the assertions (pm.expect) are being triggered.

This is because as you have already mentioned, the data is in an array. So is incorrect and should be jsonData[0].id.

const jsonData = pm.response.json(); 


pm.test("Data for ID is correct", () => {
    if (jsonData[0].id === "04e7e4ac") {
        pm.expect(jsonData[0].title).to.eql("Simple rules & mistakes to avoid")

Having IF statement on tests is bad practice. I would recommend sorting your test data out so that the responses are consistent so you don’t have to do this.

I also recommend having this as separate tests, because if the assertion for the title fails, then it won’t run the assertion for the slug. It will stop on the first failing test.

Have them as separate tests so if multiple elements fail, then you get the feedback for all of the failing elements.

Thank you for the advice! I will rework the tests so that they arent reliant on IF statements and get them separated out. :slight_smile:

Do you know if there is a way that i can write out a test without the use of IF statements that checks the data for the ID is correct if present?

What you have should already work.


If the element doesn’t exist (which would return undefined) or is a different value, the test will fail.