Postman - how to check if one of three fields it not null

Viewed 15

I am getting an API response which provides a variety of fields. Among them, there are three fields, where 2 of the 3 fields will be null and one will not be null.

How do I check, among the three fields, one is not null?

1 Answers

At least one not null

You can use the Object.values() and some() if you want at least one to be not null.

pm.test("One not null", () => {
    const parsedResponseBody = pm.response.json();
    pm.expect(Object.values(parsedResponseBody).some(v => v !== null)).to.be.true;
})

Test will success for a response body like this:

{
    "prop1": null,
    "prop2": null,
    "prop3": "notNull"
}

and for a response body like this:

{
    "prop1": null,
    "prop2": "notNull",
    "prop3": "notNull"
}

Exactly one not null

If you don't know what the other values will be

For exactly one you can just count the occurrences of a specific value (null in this case) using reduce().

This is most-likely what you want and it's very simple to customize e.g. if you suddenly want exactly 2, 3, 4, etc. values to be non-null.

pm.test("Expected count not null", () => {
    const parsedResponseBody = pm.response.json();
    const expectedCount = 1;
    pm.expect(
        Object.values(parsedResponseBody)
        .reduce((total, value) => value !== null ? total + 1: total, 0)
    ).to.equal(expectedCount);
})

Test will success for a response body like this:

{
    "prop1": null,
    "prop2": null,
    "prop3": "notNull"
}

but fail for a response body like this and for a response body like this:

{
    "prop1": null,
    "prop2": "notNull",
    "prop3": "notNull"
}

If you know what the other property values will be

If you know which values the other properties will have you can also use the following approach using all.members()

pm.test("Expected count not null", () => {
    const parsedResponseBody = pm.response.json();
    pm.expect(Object.values(parsedResponseBody)).to.have.all.members([null, null, "notNull"])
})
Related