Postman allows you to write automated test scripts to validate API responses. These scripts run after a request is sent and help ensure correctness, reliability, and consistency of APIs using JavaScript and the built-in pm object.
Postman test scripts are written in JavaScript and executed in a sandbox. The pm object provides methods to access request data, responses, environment variables, and assertion helpers.
pm.test() – Define a test casepm.expect() – Write assertionspm.response – Access API responsepm.environment – Work with environment variables
// Verify that the response status code is 200
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// Validate a JSON response property
pm.test("Response has userId", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("userId");
});
If the API response meets the defined conditions, the test passes. Otherwise, Postman marks it as failed and displays an error message, helping you quickly identify issues.
The basic execution flow in Postman:
Click a button below to simulate an API response. The test script checks for Status 200.
// The Active Test Script
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});