0
0
Postmantesting~15 mins

Using Chai assertion library in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify API response status and body using Chai assertions in Postman
Preconditions (2)
Step 1: Send a GET request to https://jsonplaceholder.typicode.com/posts/1
Step 2: In the Tests tab, write Chai assertions to verify the response status is 200
Step 3: Verify the response body contains userId equal to 1
Step 4: Verify the response body has a title property that is a non-empty string
✅ Expected Result: Test script runs successfully with all assertions passing, confirming status 200 and correct response body properties
Automation Requirements - Postman test scripts with Chai assertion library
Assertions Needed:
response status is 200
response body userId equals 1
response body title is a non-empty string
Best Practices:
Use pm.response.to.have.status for status code assertion
Parse response JSON once and reuse it
Use descriptive assertion messages
Avoid hardcoding values except for test verification
Automated Solution
Postman
pm.test('Status code is 200', () => {
    pm.response.to.have.status(200);
});

const responseJson = pm.response.json();

pm.test('userId is 1', () => {
    pm.expect(responseJson.userId, 'userId should be 1').to.eql(1);
});

pm.test('title is a non-empty string', () => {
    pm.expect(responseJson.title, 'title should be a non-empty string').to.be.a('string').and.not.empty;
});

The first test checks the HTTP status code is exactly 200 using pm.response.to.have.status(200). This confirms the request succeeded.

Next, we parse the response JSON once with pm.response.json() and store it in responseJson to avoid repeated parsing.

The second test asserts that the userId property equals 1 using pm.expect().to.eql() with a clear message.

The third test verifies the title property is a string and not empty using chained Chai assertions .to.be.a('string').and.not.empty. This ensures the title is valid text.

Each assertion has a descriptive message to help understand failures. This script follows Postman and Chai best practices for clarity and efficiency.

Common Mistakes - 3 Pitfalls
Not parsing response JSON before accessing properties
{'mistake': 'Using pm.expect(pm.response.code).to.equal(200) instead of pm.response.to.have.status(200)', 'why_bad': "Less readable and does not use Postman's built-in status assertion which gives better error messages", 'correct_approach': 'Use pm.response.to.have.status(200) for status code assertions'}
Hardcoding assertion values without descriptive messages
Bonus Challenge

Now add data-driven testing with 3 different post IDs (1, 2, 3) verifying the same assertions for each

Show Hint