Trouble validating a response json

Hi everyone,
I’m currently trying to build a test collection for some requests that I’d like to monitor. Idea is to simply run these tests for the whole collection whenever needed.

Most of my first tests were easy copy and paste and they do work, just like:

pm.test("Response contains an object", () => {
    var jsonData = pm.response.json();
    console.log(jsonData);
    pm.expect(jsonData).to.be.an("object");
    pm.expect(jsonData.id).to.be.a("number");
});

As you can see, my requests returns a specific object. It looks like this (I just changed some key names):

{
    "id": 123,
    "string1": "abc",
    "string2": "def",
    "string3": "ghi"
}

Now I would like to test if a set of keys is actually included in the response. From the documentation, I copied:

pm.test("debug", () => {
    pm.expect({a: 1, b: 2}).to.have.all.keys("a","b");
});

This example works as expected. But if I do the same for my request:

pm.test("Object contains desired keys", () => {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.be.an("object"); // ok
    console.log("type: " + typeof(jsonData)); //returns "object"
    console.log("id: " + jsonData.id);  //returns the expected id
    console.log(jsonData); //pints json object to console
    pm.expect(jsonData.id).to.equal(123); //validates correctly
    pm.expect(jsonData.id).to.be.a("number") //works too
    pm.expect(jsonData).to.have.all.keys("id", "string1"); //does not work
    pm.expect(jsonData).to.have.key("id"); //does not work
});

the result page shows the failed test like this:

I’m quite a new user and would appreciate any help/thoughts on this :slight_smile:

thank you in advance,
m.

The assertion failed due to it chacking against all the keys in the object and then matching that to your values.

This would work as it has all the keys:

pm.expect(jsonData).to.have.all.keys('id', 'string1', 'string2', 'string3');

You could use something like this:

pm.expect(jsonData, `Value not included in the list of Keys ${_.keys(jsonData)}`).to.include.keys('id', 'string1');

I added a message in the expect statement which shows you the keys that it’s checking against.

1 Like

Many thanks @dannydainton ! That was really helpful and solved my issue. I was simply assuming the “all” refers to the list of keys I’d like to check for.

1 Like