Introduction
Response body assertions check if the data returned from an API is correct. This helps make sure the API works as expected.
Jump into concepts and practice - no test required
Response body assertions check if the data returned from an API is correct. This helps make sure the API works as expected.
pm.test("Test description", function () {
let jsonData = pm.response.json();
pm.expect(jsonData.key).to.eql(expectedValue);
});Use pm.response.json() to parse the response body as JSON.
Use pm.expect() with to.eql() to compare values exactly.
name field equal to "Alice".pm.test("Check user name", function () { let jsonData = pm.response.json(); pm.expect(jsonData.name).to.eql("Alice"); });
pm.test("Verify product count", function () { let jsonData = pm.response.json(); pm.expect(jsonData.products.length).to.eql(5); });
pm.test("Error message present", function () { let jsonData = pm.response.json(); pm.expect(jsonData.error).to.include("Invalid request"); });
This test verifies that the response body contains a userId of 12345 and a status of "active".
pm.test("Response body has correct user ID and status", function () { let jsonData = pm.response.json(); pm.expect(jsonData.userId).to.eql(12345); pm.expect(jsonData.status).to.eql("active"); });
Always parse the response body before making assertions.
Use clear test names to describe what you are checking.
Check for both exact matches and partial matches depending on your needs.
Response body assertions check the data returned by an API.
Use pm.response.json() to read the response body.
Write clear tests to confirm the API returns expected values.
pm.response.json() do in Postman tests?pm.response.json()pm.response.json().status with value success in Postman?pm.expect() with Chai assertion style, so pm.expect(pm.response.json().status).to.eql('success'); is correct.{"user":{"id":5,"name":"Alice"}} What will this test output?const jsonData = pm.response.json();
pm.test("User ID is 5", () => {
pm.expect(jsonData.user.id).to.equal(5);
});jsonData.user.id is 5.jsonData.user.id equals 5, which is true, so the test passes.const data = pm.response.json();
pm.test("Check user name", () => {
pm.expect(data.user.name).to.equal('Bob')
});pm.test correctly, with proper arrow function and assertion syntax.items contains an object with id equal to 10. Which test code correctly checks this in Postman?items is an array of objects; we want to check if any object has id 10.some() to check if any item has id === 10, which is correct. pm.expect(pm.response.json().items.id).to.equal(10); wrongly accesses items.id (invalid). pm.expect(pm.response.json().items.includes({id:10})).to.be.true; tries to use includes() with an object, which won't work. const items = pm.response.json().items;
pm.expect(items.find(id => id === 10)).to.exist; uses find() but the callback is incorrect (should check item.id).