0

I want to verify the response data as a test using Postman. For example, given the response below:

{
  "data": {
    "id": 2,
    "first_name": "Janet",
    "last_name": "Weaver",
    "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"
  }
}

How do I verify this response body as a test?

0

As @Mache says, you search for each value.

var jsonData = pm.response.json(); 
pm.test("Verify Json values", function () { 
    pm.expect(jsonData.data.id).is.to.equal(2); 
    pm.expect(jsonData.data.first_name).is.to.equal("Janet"); 
    pm.expect(jsonData.data.last_name).is.to.equal("Weaver"); 
    // and so on and so on
});

The better option:

Create test cases for each assertion

var jsonData = pm.response.json(); 
pm.test("Verify data ID", function () { 
        pm.expect(jsonData.data.id).is.to.equal(2); 
    });
pm.test("Verify first_name", function () { 
        pm.expect(jsonData.data.first_name).is.to.equal("Janet"); 
    });
pm.test("Verify last_name", function () { 
        pm.expect(jsonData.data.last_name).is.to.equal("Weaver"); 
    });

Another option

This will give you a better view on what actually went wrong or is not present on your json response body.

If you really wish to compare the full body, you can create a variable with the expected outcome in a pre-request script like so:

var expectedJsonBody =
{
  "data": {
    "id": 2,
    "first_name": "Janet",
    "last_name": "Weaver",
    "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"
  }
}

pm.environment.set("address", JSON.stringify(expectedJsonBody));

in your request test, you compare the response body with the variable.

0

After the obvious - Status code is 2xx you need to add tests based on content:

var jsonData = pm.response.json(); 
pm.test("Verify first_name", function () { 
    pm.expect(jsonData.first_name).is.to.equal("Janet"); 
});

You can check this answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.