最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Postman: How to check the data type of each value in a response - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question edited May 25, 2020 at 14:10 n-verbitsky 5522 gold badges9 silver badges20 bronze badges asked Feb 13, 2018 at 22:35 pgtipspgtips 1,3386 gold badges24 silver badges44 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

This 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)

发布评论

评论列表(0)

  1. 暂无评论