thegoatboy
thegoatboy

Reputation: 63

Postman API testing: Unable to assert a value is true

I am testing an API with a GET request that returns the following data:

    {
    "Verified": true,
    "VerifiedDate": 2018-10-08
}

I am trying to test that the first field comes back true, and the second field has a value. I have the following code:

    pm.test("Verified should be true", function () {
   var Status = pm.response.json();
   pm.expect(Status.Verified).to.be.true;
});

    pm.test("Returns a verified date", function () {
   var Status = pm.response.json();
   pm.expect(Status.VerifiedDate).to.not.eql(null);

});

The assert on true is failing for the following reason:

Verified should be true | AssertionError: expected undefined to be true

Why is the first test failing?

I am running the same test on a post command without any issues.

Any ideas?

thanks

Upvotes: 4

Views: 12337

Answers (2)

Danny Dainton
Danny Dainton

Reputation: 25921

You could also just do this:

pm.test('Check the response body properties', () => {
    _.each(pm.response.json(), (item) => {
        pm.expect(item.Verified).to.be.true
        pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/)
    })
})

The check will do a few things for you, it will iterate over the whole array and check that the Verified property is true and also check that the VerifiedDate is a string and matches the YYYY-MM-DD format, like in the example given in your question.

Upvotes: 1

Nguyen Quoc Dung
Nguyen Quoc Dung

Reputation: 76

Root cause: Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare.

Solution: Use exactly value of an item in the list with if else command to compare.

var arr = pm.response.json(); 
console.log(arr.length) 
for (var i = 0; i < arr.length; i++)
{ 
    if(arr[i].Verified === true){
        pm.test("Verified should be true", function () {
            pm.expect(arr[i].Verified).to.be.true;
        });
    }
    if(arr[i].Verified === false){
        pm.test("Verified should be false", function () {
            pm.expect(arr[i].Verified).to.be.false;
        });
    }     
}

Hope it help you.

Upvotes: 6

Related Questions