How do I check that the data type of each value in an API response is NOT an integer?
For example, if my API returns this:
"teamPermissions": [
"Edit",
"Administrator",
"ReadOnly",
etc
]
I need a Postman test to make sure that an integer is never returned in the teamPermission
array.
Here's what I started but need assistance:
var jsonData = JSON.parse(responseBody);
tests["Team Permissions Do Not Contain Integers"] = typeof(jsonData.teamPermissions) !== "number"
This passes because teamPermissions
is an object but how do I check each value of the object is not an integer?
How do I check that the data type of each value in an API response is NOT an integer?
For example, if my API returns this:
"teamPermissions": [
"Edit",
"Administrator",
"ReadOnly",
etc
]
I need a Postman test to make sure that an integer is never returned in the teamPermission
array.
Here's what I started but need assistance:
var jsonData = JSON.parse(responseBody);
tests["Team Permissions Do Not Contain Integers"] = typeof(jsonData.teamPermissions) !== "number"
This passes because teamPermissions
is an object but how do I check each value of the object is not an integer?
3 Answers
Reset to default 15This should do the check for you:
pm.test('Not contain numbers', () => {
var jsonData = pm.response.json()
for (i = 0; i < jsonData.teamPermissions.length; i++) {
pm.expect(jsonData.teamPermissions[i]).to.not.be.a('number')
}
})
Here's what the check will do if a number is part of the array, I've logged out the types so you can see what it's checking against.
Another alternative is to use Lodash, it's a build-in module for the Postman native app. This code will run the same check as the one above:
pm.test('Not contain numbers', () => {
_.each(pm.response.json().teamPermissions, (arrItem) => {
pm.expect(arrItem).to.not.be.a('number')
})
})
It looks like teamPermissions
is an Array.
You could use Array.prototype.every()
to check if all the elements pass some condition:
var array1 = [1, 2, 3];
var array2 = ["a", 9, 10];
console.log(array1.every((e) => { return !isNaN(e) })) // True, all elements are numbers
console.log(array2.every((e) => { return !isNaN(e) })) // False
I assume you can do something like this:
jsonData.forEach((a)=>{
var boolVal=isNaN(a) ? true : false
if(boolVal)
{
tests["Team Permissions Do Not Contain Integers"]=false;
}
});
FYI , Instead isNaN(a) you can also do Number.isInteger(a)