Testing with Postman: Chai Assertions

Postman logo: the orange Postman astronaut

Postman uses the Chai Assertion Library, so Postman Chai assertions are worth getting familiar with.

Postman logo: the orange Postman astronaut

Common Postman Chai Assertions

Before you get into regex, most of your tests will lean on a handful of Postman Chai assertions. Status codes, whether a field exists, what type it is, and what it equals cover a lot of ground. Chai reads almost like a sentence, so pm.expect(x).to.be.a("string") does exactly what it says.

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Response has the fields we expect", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property("id");    // the field exists
    pm.expect(jsonData.name).to.be.a("string");    // the field is the right type
    pm.expect(jsonData.tags).to.include("qa");     // an array contains a value
    pm.expect(jsonData.total).to.eql(3);           // deep equality
});

Each pm.expect takes an optional message as a second argument, just like the date example below. Use it. When a test fails at 2 AM in a pipeline, “Date should be 0000-00-00T00:00:00Z” tells you a lot more than “expected false to be true.”

Using Chai Match Assertion

You can define a format for your response using Regex and the match assertion. Below is an example of a data format for a mysql date.

Date Format

pm.test("Date is correct format", function() {
            pm.expect(jsonData.date).to.match(/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$/, "Date should be 0000-00-00T00:00:00Z not " + jsonData.date);
        });

Multiple Assertions

When using multiple assertions on a single data point you don’t need to create an a new pm.expect. Instead use and and a proper error message. Since a proper error message is there you will know what has happened.

And

pm.expect(jsonData.smallsString).to.be.a('string', 'smallsString is not a string')
     .and.be.lengthOf(5, 'smallsString is not 5 in length')
     .and.to.contain('den', 'smallsString does not contain den')

See the below Chai Assertion Library link for more on Chai Assertions.

More Testing with Postman

Links

Postman Quick Reference Guide
Chai Assertion Library
Regex Cheat Sheet
Postman: The Complete Guide on Udemy