← Back to Chapters

Writing Test Scripts in Postman

? Writing Test Scripts in Postman

? Quick Overview

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.

? Key Concepts

  • pm Object – Core Postman API for tests, variables, and responses
  • Tests Tab – Section where test scripts are written
  • Assertions – Conditions that must pass for a test to succeed
  • Test Structure – Organizing tests for clarity and reuse

? Syntax / Theory

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 case
  • pm.expect() – Write assertions
  • pm.response – Access API response
  • pm.environment – Work with environment variables

? Code Example(s)

? View Code Example
// Verify that the response status code is 200
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
? View Code Example
// Validate a JSON response property
pm.test("Response has userId", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("userId");
});

? Live Output / Explanation

What Happens?

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.

? Interactive Example / Visual Flow

The basic execution flow in Postman:

  1. Request is sent
  2. Response is received
  3. Test scripts execute
  4. Results appear in the Tests tab
?️ Mini Postman Simulator

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);
});
Results will appear here...

? Use Cases

  • Automated API testing
  • Regression testing during development
  • Validating response schemas
  • CI/CD pipeline integration

✅ Tips & Best Practices

  • Write small, focused tests
  • Use meaningful test names
  • Group related assertions logically
  • Reuse logic with environment and global variables

? Try It Yourself

  1. Send a GET request to a public API
  2. Write a test to check status code
  3. Validate a response field
  4. Intentionally break a test and observe the failure