Skip to content

Postman Testing Deep Dive — Advanced API Testing with Postman

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Postman Testing Deep Dive. We cover key concepts, practical examples, and best practices to help you master this topic.

Postman provides a comprehensive API testing environment with a collection runner for sequential test execution, scriptable pre-request and test stages, and environment variables for configuration.

What You'll Learn

Postman collection runner configuration, request chaining with variables, advanced test scripts with Chai assertions, collection-level vs request-level scripts, and integrating Postman tests with CI/CD.

Code Example, Practice, FAQ, Mini Project sections follow the standard template.

Code Example: Test Scripts with Chai Assertions

// Tests tab for POST /api/v1/threats
const response = pm.response;

// Status code assertion
pm.test("Status code is 201 Created", function () {
    pm.response.to.have.status(201);
});

// Response body assertions
pm.test("Response has correct threat structure", function () {
    const jsonData = pm.response.json();

    pm.expect(jsonData).to.have.property("id");
    pm.expect(jsonData).to.have.property("name");
    pm.expect(jsonData).to.have.property("severity");
    pm.expect(jsonData).to.have.property("created_at");
    pm.expect(jsonData.name).to.eql("SQL Injection Attempt");
});

// Response time assertion
pm.test("Response time is less than 500ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

// Header assertions
pm.test("Content-Type header is present", function () {
    pm.response.to.have.header("Content-Type");
    pm.expect(pm.response.headers.get("Content-Type"))
      .to.include("application/json");
});

// Save values for subsequent requests
pm.test("Save threat ID for next request", function () {
    const jsonData = pm.response.json();
    pm.collectionVariables.set("threatId", jsonData.id);
    pm.environment.set("lastCreatedThreat", jsonData.id);
});

Code Example: Pre-Request Scripts

// Pre-request tab for GET /api/v1/threats/:id
// Generate dynamic test data
const timestamp = Date.now();
pm.variables.set("timestamp", timestamp);

// Set request parameters
pm.request.url.query.add({
    key: "_t",
    value: timestamp
});

// Generate auth token if not present
const token = pm.environment.get("authToken");
if (!token) {
    console.log("No auth token found, triggering login...");
    pm.sendRequest({
        url: `${pm.environment.get("baseUrl")}/api/auth/login`,
        method: "POST",
        header: { "Content-Type": "application/json" },
        body: {
            mode: "raw",
            raw: JSON.stringify({
                username: pm.environment.get("testUsername"),
                password: pm.environment.get("testPassword")
            })
        }
    }, function (err, response) {
        if (!err) {
            const token = response.json().access_token;
            pm.environment.set("authToken", token);
        }
    });
}

// Set auth header
pm.request.headers.add({
    key: "Authorization",
    value: `Bearer ${pm.environment.get("authToken")}`
});

Code Example: Data-Driven Testing with CSV/JSON

name,severity,source_ip,expected_status
SQL Injection,high,10.0.0.1,201
XSS Attack,medium,10.0.0.2,201
Brute Force,low,,201
Invalid Severity,ultra-high,10.0.0.4,422
Missing Name,,10.0.0.5,422
// Collection-level pre-request to iterate over data file
const data = pm.iterationData.get("name");
const severity = pm.iterationData.get("severity");

pm.variables.set("threatName", data);
pm.variables.set("threatSeverity", severity);

// Tests for data-driven iteration
const expectedStatus = parseInt(pm.iterationData.get("expected_status"));

pm.test(`Status code is ${expectedStatus}`, function () {
    pm.response.to.have.status(expectedStatus);
});

pm.test("Response matches data-driven input", function () {
    if (pm.response.code === 201) {
        const jsonData = pm.response.json();
        pm.expect(jsonData.name).to.eql(pm.iterationData.get("name"));
    }
});

Common Mistakes

1. Hardcoding Values in Tests

Use environment variables, collection variables, and data files. Hardcoded values break when running against different environments or datasets.

2. Not Validating Response Structure

Assert on specific fields and types, not just status codes. Validate that required fields exist and have the correct data type.

3. Ignoring Response Time

APIs can return correct data but be too slow. Add response time assertions to catch performance regressions.

4. Script Errors Silently Failing

JavaScript errors in test scripts cause tests to pass without assertions. Use pm.test wrappers and catch errors in pre-request scripts.

5. Not Cleaning Up Test Data

Tests that create resources should clean up afterward. Use a final request in the collection to delete created resources.

Practice Questions

  1. What is the difference between collection variables and environment variables?
  2. How do you chain requests in a Postman collection?
  3. What is data-driven testing and how does Postman support it?
  4. How do pre-request scripts differ from test scripts?
  5. How do you run Postman collections in CI/CD?

Answers:

  1. Collection variables are scoped to a collection and shared across requests. Environment variables are scoped to an environment (dev, staging, prod) and can be switched.
  2. Use pm.collectionVariables.set() in test scripts to store values from one response, then reference them as {{variableName}} in subsequent requests.
  3. Data-driven testing runs the same collection with multiple data sets from CSV or JSON files. Each iteration uses a different row of data.
  4. Pre-request scripts run before the request is sent (setup auth, generate data). Test scripts run after the response is received (validate results).
  5. Export the collection as JSON, use Newman (Postman's CLI) to run it: newman run collection.json -e environment.json -d data.csv.

Challenge: Build a complete Postman collection for a threat management API with collection-level variables, pre-request authentication, request chaining, data-driven tests for threat creation, and response validation with Chai assertions.

FAQ

Can Postman test GraphQL APIs?

Yes. Postman supports GraphQL queries, variables, and schema introspection. Use the GraphQL body type and write tests for the response structure.

How do I debug Postman test scripts?

Use console.log() statements and view the output in Postman's console (View > Show Postman Console). Check the Postman console for error messages.

Can I use external libraries in Postman?

Postman supports Sandbox libraries (Chai, CryptoJS, tv4, etc.) but not arbitrary npm packages. For custom logic, use pre-request or test scripts.

How do I handle file uploads in Postman tests?

Use the form-data body type with a file reference. In test scripts, verify the file was accepted by checking the response for file metadata.

Should I store Postman collections in version control?

Yes. Export collections as JSON and commit them. Use Postman's API or Postman CLI to sync collections with the workspace.

Mini Project

Build a Postman collection for a threat intelligence API with: environment variables for dev/staging/prod, pre-request script for automatic token generation, request chaining (create threat, fetch threat, update threat), data-driven tests for validation, and response time assertions.

What's Next

Now learn about Postman Pre-Request and Test Scripts for advanced scripting in Postman.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro