POSTMAN: Comparing object Environment variable with response's object

I am having a problem with comparing object typed Env variable with the response’s object in Postman even though it seems the same and couldn’t find answers anywhere.

Here’s the example:

The object used is:

"user": 
{
  "id" = 1,
  "first_name": "John",
  "last_name": "Smith"
}

When using a POST request I save the object as Environment Variable using:

var reqdata = JSON.parse(data.request);
postman.setEnvironmentVariable("User", JSON.stringify(reqdata.user));

and then in a GET response I want to compare it by using:

Pre-request Script:

user = JSON.parse(postman.getEnvironmentVariable("User"));

and then in Tests:

var data = JSON.parse(responseBody);
tests["user contains correct data"] = data.user == user;
    console.log(data.user);
    console.log(user);

The console.log returns exactly the same objects but I am still getting fail. I tried using Object.is() and === but it still returns fail. Could somebody please tell me what I am missing?

Cheers

26 thoughts on “POSTMAN: Comparing object Environment variable with response's object”

  1. I have found a solution, I’ve used:

    tests["user contains correct data" = JSON.stringify(data.user) == JSON.stringify(user);
    

    And I can also just delete the test script and use bare postman.getEnvironmentVariable instead of the second stringify().

    Reply
  2. You can find better solutions to your problem in a very similar question here:
    How to write a postman test to compare the response json against another json?

    I had a similar problem to solve except that my JSON also contained an array of objects.
    My answer in this question or one of the other answers will provide a more stable solution for comparison.

    I created an array of global functions called "assert", which contained helper functions such as "areEqual" and "areArraysOfObjectsEqual" and saved these under the "Tests" tab at a top folder level of my tests.

    Reply

Leave a Comment