mercredi 27 mars 2019

How to verify if a node that might either contain a null or a string in the response body using Postman?

I need to verify whether a particular node in the response body of an API is null or a string. How is it done using ChaiJS in postman tests?

Sample API response body:

[
 {
   "exercise_num": "1",
   "expire_date": "2019-03-11T16:31:17.935Z",
   "created_at": "2019-03-15T11:44:35.698Z"
 },
 {
    "exercise_num": "2",
    "expire_date": null,
    "created_at": "2019-03-15T11:44:38.363Z"
 }
]

I would like to verify that the expire_date node in the above sample API response body will either only contain null or a string data type and it won't return any other data type such as int, etc.

I have tried the following:

var jsonData = JSON.parse(responseBody);
pm.test('All expire_date contains either string or null', () => {
for (i = 0; i < jsonData.length; i++) {
if(jsonData[i].expire_date === null){
tests["expire_date is null"] = true;
}
else{
    pm.expect(jsonData[i].expire_date).to.be.a('string');
}
}
});

The test passes.

I'm expecting if something like this can be done:

pm.test('All expire_date contains string', () => {
for (i = 0; i < jsonData.length; i++) {
    pm.expect(jsonData[i].expire_date).to.be.a('string' || null);
}
});

Aucun commentaire:

Enregistrer un commentaire