</>

Technology

Postman

Difficulty

Intermediate

Interview Question

How do you validate JSON responses in Postman test scripts?

Answer

Validating JSON Responses in Postman

Use pm.response.json() to parse the response body as a JavaScript object and then apply assertions using Chai.js (built into Postman).

Basic JSON Validation

JavaScript
const jsonData = pm.response.json();

// Check a field equals specific value
pm.test("User ID is 2", function () {
    pm.expect(jsonData.data.id).to.eql(2);
});

// Check field type
pm.test("Email is a string", function () {
    pm.expect(jsonData.data.email).to.be.a("string");
});

// Check field exists
pm.test("First name exists", function () {
    pm.expect(jsonData.data).to.have.property("first_name");
});

// Check string contains value
pm.test("Email contains @", function () {
    pm.expect(jsonData.data.email).to.include("@");
});

Array Validation

JavaScript
const jsonData = pm.response.json();

// Check array length
pm.test("Data has 6 users", function () {
    pm.expect(jsonData.data).to.have.lengthOf(6);
});

// Check first element
pm.test("First user ID is 1", function () {
    pm.expect(jsonData.data[0].id).to.eql(1);
});

// Check all emails are strings
pm.test("All emails are valid", function () {
    jsonData.data.forEach(user => {
        pm.expect(user.email).to.be.a("string");
        pm.expect(user.email).to.include("@");
    });
});

Nested Object Validation

JavaScript
pm.test("Support URL exists", function () {
    pm.expect(jsonData.support.url).to.be.a("string");
    pm.expect(jsonData.support.url).to.match(/^https/);
});

Common Chai Assertions

AssertionExample
Equal.to.eql("value")
Include.to.include("text")
Type check.to.be.a("string")
Property exists.to.have.property("id")
Number comparison.to.be.above(0)
Array length.to.have.lengthOf(5)
Not null.to.not.be.null
Match regex.to.match(/pattern/)

Follow AutomateQA

Related Topics