0
0
Postmantesting~5 mins

Tests tab and pm.test() in Postman

Choose your learning style9 modes available
Introduction

The Tests tab in Postman lets you write checks to see if your API works as expected. pm.test() helps you write these checks easily.

After sending an API request to check if the response status is correct.
To verify if the response body contains the expected data.
To confirm that response headers have the right values.
When you want to automate checking your API without manual inspection.
To create reports showing which tests passed or failed.
Syntax
Postman
pm.test("Test name", function () {
    pm.expect(actual).to.eql(expected);
});

pm.test() takes two parts: a name for the test and a function with the check.

Inside the function, use pm.expect() to compare actual and expected results.

Examples
This test checks if the response status code is 200 (OK).
Postman
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
This test checks if the response JSON has a name field equal to "Alice".
Postman
pm.test("Response has user name", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData.name).to.eql("Alice");
});
This test verifies the response header Content-Type is exactly "application/json".
Postman
pm.test("Content-Type is JSON", function () {
    pm.response.to.have.header("Content-Type", "application/json");
});
Sample Program

This script runs two tests: one checks the status code is 200, the other checks the user ID in the response JSON is 123.

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

pm.test("Response has correct user ID", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData.id).to.eql(123);
});
OutputSuccess
Important Notes

Always give your tests clear, descriptive names so you know what they check.

If a test fails, Postman shows which test and why, helping you fix issues quickly.

You can write many tests in the Tests tab to cover different parts of the response.

Summary

The Tests tab lets you write checks to verify API responses automatically.

pm.test() defines a test with a name and a check function.

Use pm.expect() inside pm.test() to compare actual and expected values.