0
0
Postmantesting~15 mins

JSON value assertions in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify JSON response values in Postman
Preconditions (2)
Step 1: Send a GET request to https://api.example.com/user/123
Step 2: Check that the response status code is 200
Step 3: Verify the JSON response contains a 'name' field with value 'John Doe'
Step 4: Verify the JSON response contains an 'age' field with value 30
Step 5: Verify the JSON response contains a 'roles' array that includes 'admin'
✅ Expected Result: The response status is 200 and all JSON fields have the expected values
Automation Requirements - Postman Tests (JavaScript)
Assertions Needed:
Status code equals 200
'name' field equals 'John Doe'
'age' field equals 30
'roles' array contains 'admin'
Best Practices:
Use pm.response.to.have.status for status code assertion
Parse JSON response once and reuse it
Use pm.expect for assertions
Write clear and descriptive assertion messages
Automated Solution
Postman
pm.test('Status code is 200', () => {
    pm.response.to.have.status(200);
});

const jsonData = pm.response.json();

pm.test('Name is John Doe', () => {
    pm.expect(jsonData.name, 'Check name field').to.eql('John Doe');
});

pm.test('Age is 30', () => {
    pm.expect(jsonData.age, 'Check age field').to.eql(30);
});

pm.test('Roles include admin', () => {
    pm.expect(jsonData.roles, 'Check roles array').to.include('admin');
});

This Postman test script first checks the HTTP status code is 200 using pm.response.to.have.status(200). Then it parses the JSON response once with pm.response.json() and stores it in jsonData for reuse.

Each field is checked with pm.expect assertions: the name field must equal 'John Doe', the age field must equal 30, and the roles array must include the string 'admin'.

Descriptive messages are added to each assertion to help understand failures.

Common Mistakes - 4 Pitfalls
Parsing JSON response multiple times
Using incorrect assertion methods for status code
Not checking if array contains expected value properly
Hardcoding values without clear messages
Bonus Challenge

Now add data-driven testing with 3 different user IDs and verify their names and ages

Show Hint