David
David

Reputation: 175

Postman test array response with various values

I created a test for looping through an array returned in a response in Postman, which checks a value for name 'power', which has value 0. This is a CONSTANT value so the test passes in the loop. The question is how to test 'timestamp' which does not have a constant value (in this example) and cannot be done in a loop

i.e.

pm.test('Test Array - power values', function() {
var body = JSON.parse(responseBody);

for(var i=0; i < body.powerReadings.length; i++) {
    console.log("test"  + i + body.powerReadings[i].power)
    pm.expect(body.powerReadings[i].power).to.eql(0)
}
});

An extract from the response array is as follows:

"powerReadings": [
    {
        "timestamp": "2018-10-05T10:30:11.330Z",
        "power": 0
    },
    {
        "timestamp": "2018-10-05T10:30:26.352Z",
        "power": 0
    }
]

Upvotes: 5

Views: 10249

Answers (1)

Danny Dainton
Danny Dainton

Reputation: 25851

This would check those:

pm.test("Test Array - power values", () => {
    let jsonData = pm.response.json();

    _.each(jsonData.powerReadings, (item) => {
        pm.expect(item.power).to.eql(0)
        pm.expect(item.timestamp).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[.]\d{3}Z$/)
    })
})

It doesn't solved the problem of the actual value of the timestamp though.

Upvotes: 4

Related Questions