Handling Array Responses in Postman Tests

Handling Array Responses in Postman Tests

While working on a Postman test script for a response, I encountered an issue where my test was consistently failing. The response I was testing looked like this:

[
    {
        "message": "Session expired or invalid",
        "errorCode": "INVALID_SESSION_ID"
    }
]

Initially, I assumed the response was a single JSON object, so I wrote the following test:

let response = pm.response.json();
pm.expect(response.message).to.eql("Session expired or invalid");

However, this approach caused an error because the response is actually an array containing a single object, not a standalone object. Accessing response.message directly was incorrect, as response is an array and does not have a message property.

Solution: Accessing the Array Properly

To resolve the issue, I adjusted the script to account for the array structure. First, I validated that the response is an array and contains at least one item. Then, I accessed the first object in the array (response[0]) to validate the message field. Here’s the corrected script:

let response = pm.response.json();

// Check if the response is an array and has at least one item
pm.test("Response is an array with at least one item", function () {
    pm.expect(response).to.be.an("array").that.is.not.empty;
});

// Access the first item in the array and validate the message
pm.test("Message is 'Session expired or invalid'", function () {
    pm.expect(response[0].message).to.eql("Session expired or invalid");
});

This approach ensures the test script properly handles the array structure of the response and avoids runtime errors. The first test verifies the response structure, while the second test confirms the specific value of the message property. This adjustment solved the problem, and my tests now pass successfully.

Scroll to Top