Search code examples
javascripttestingpostmanbddchai

How to test for absence of (potentially) nested JSON properties in Postman?


I want to test for absence of the nested property "x"

The test must fail if, the response looks like this

A:

{
    "first": 1,
    "second": {
        "one": 1,
        "two": 2,
        "three": {
            "x": 1,
            "y": 2
        }
    }
}

But for the following examples it must pass:

B:

{
    "first": 1,
    "second": {
        "one": 1,
        "two": 2,
        "three": {
            "y": 2
        }
    }
}

C:

{
    "first": 1,
    "second": {
        "one": 1,
        "two": 2
    }
}

D:

{
    "first": 1
}

Of course. I can use pm.expect(object).to.not.have.property("x") to test for the absence. But this wouldn't be helpful in all cases.

For example, my PostMan test-code:

pm.test("(nested)property 'x' not available", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.second.three).to.not.have.property("x")
});

would work great for the cases A and B, but not for C and D, because the parents "second" or "three" of the property can be undefined. But i dont want to test for the absence of them, because its not the target of this specific test.

Is there any BDD Chai function, that delivers this functionality or am i forced to implement a recursive helper function for this case?


Solution

  • You can make use of the inbuilt Lodash functions to breakdown the data more, rather than trying to do it all in the pm.expect() statement.

    The _.get() function might be a useful one to explore that with - https://lodash.com/docs/4.17.11#get