Verifying an array response of numbers contains all odd numbers

I have a response that returns an array of numbers. All of these numbers should be odd numbers. If there is an even number in the array I want the test to fail.

I’m thinking a function that determines if the value from the array is odd or not but I am not sure how to write this.

For instance if I use:
function isOdd(x) {
Math.abs(x % 2) == 0
}

How do I call the function for each of the values in the array?

Here is an example of the response:
“responsePacket”: {
“returnedData”: {
“Array”: “1171, 29, 1017, 1479, 122, 115, 1837, 1335, 1403”
}
}
}

Something like this that will iterate through the list:
var jsonData = pm.response.json();

pm.test("Verify Odd Numbers", function () { 

    pm.expect(isEven(jsonData.responsePacket.Array)); 

});

Hi @shales03,

You can use .satisfy() to accomplish this.

Example:

const isOdd = (n) => Math.abs(n % 2) == 1;
pm.test("should be an array with only odd numbers", () => {
    const subject = jsonData.responsePacket;
    pm.expect(subject).to.satisfy((values) => values.every(isOdd));
});

Hope that helps.

Best,

Kevin

Hi Kevin,

I was getting an error when I tried this. It was telling me that .every is not a function. Did I do something wrong?

Since I wasn’t making any progress on the error I went ahead and created a function to verify the number from the array is an odd number. I’m expecting a ‘1’, but there are times where the logic correctly identifies an even number but does not fail the test case. Do you know what I could be doing wrong in this case?

This is a GET call and the endpoint is: https://challenge.covaxdata.net/applet/api/array

var jsonData = pm.response.json();

pm.test(“should be an array with only odd numbers”, () => {
const subject = jsonData.responsePacket;
const values = subject.returnedData.Array;
var arr = values.split(’, ');
for (var i = 0; i < arr.length; i++) {
var isOdd = (arr[i] % 2)
pm.expect((isOdd) == 1)
console.log(isOdd)
}
});

Here is the solution I came up with. Probably not the most elegant solution but it seems to work:

var jsonData = pm.response.json();

pm.test(“should be an array with only odd numbers”, () => {

const subject = jsonData.responsePacket;

const values = subject.returnedData.Array;

var arr = values.split(', ');

for (var i = 0; i < arr.length; i++) {

    var isOdd = (arr[i] % 2)

    if (isOdd === 1) {

        pm.expect.pass('Only contains odd numbers')

    }

    else {

        pm.expect.fail('Contains even numbers')

    }

}

});

Hey @shales03,

The pm.expect function doesn’t evaluate an assertion; it just sets a subject to test. You’d have to do something like pm.expect(isOdd).to.eql(1) or pm.expect(isOdd === 1).to.be.true.

Best,

Kevin