0
0
Postmantesting~5 mins

Using Chai assertion library in Postman

Choose your learning style9 modes available
Introduction

Chai helps you check if your API responses are correct by making easy-to-read tests. It tells you if something is wrong so you can fix it fast.

When you want to confirm an API returns the right status code like 200 or 404.
When you need to check if the response body contains expected data.
When you want to verify headers in the API response.
When you want to make sure a value is true, false, or equals something specific.
When you want clear messages about what failed in your tests.
Syntax
Postman
pm.test('Test description', function () {
    pm.expect(actualValue).to.equal(expectedValue);
});

pm.test defines a test with a description.

pm.expect uses Chai's assertion style to check values.

Examples
Checks if the API response status code is exactly 200.
Postman
pm.test('Status code is 200', function () {
    pm.response.to.have.status(200);
});
Verifies the JSON response contains a userId field equal to 5.
Postman
pm.test('Response has userId 5', function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData.userId).to.equal(5);
});
Checks if the response text includes the word 'success'.
Postman
pm.test('Response body contains success message', function () {
    pm.expect(pm.response.text()).to.include('success');
});
Sample Program

This test checks the API returns status 200, the response JSON has a 'name' property which is a string, and an 'active' property that is true.

Postman
pm.test('Verify API response status and content', function () {
    pm.response.to.have.status(200);
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('name');
    pm.expect(jsonData.name).to.be.a('string');
    pm.expect(jsonData.active).to.be.true;
});
OutputSuccess
Important Notes

Use clear and simple test descriptions so you know what each test checks.

Chai assertions give detailed error messages to help find problems quickly.

Always parse JSON responses before checking their properties.

Summary

Chai makes writing tests easy and readable in Postman.

Use pm.test and pm.expect to create clear checks for your API responses.

Good assertions help catch bugs early and improve API quality.