1

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

Guestz0r
  • 217
  • 1
  • 3
  • 7

2 Answers2

0

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().

Guestz0r
  • 217
  • 1
  • 3
  • 7
  • 4
    careful because this is an extremely shallow comparison, as `JSON.stringify({a:1, b:2})` results in `"{"a":1,"b":2}"` while `JSON.stringify({b:2, a:1})` results in `"{"b":2,"a":1}"`. Both objects have the same attributes and values, but the comparison will fail – GChamon May 11 '18 at 14:30
0

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.

Mike
  • 827
  • 11
  • 27