Skip to content

08 Test Scripts

DodaTech 3 min read

title: "Test Scripts in Postman" description: "Write test scripts in Postman for API response validation. Learn pm.test assertions, response inspection, status code checks, body validation, header verification, and response time assertions." weight: 8 date: 2026-06-28 lastmod: 2026-06-28 tags: [api-development, postman] }

Test scripts execute after the API response is received. They validate status codes, response bodies, headers, and timing. Postman tests use the pm object and Chai assertion library for readable, maintainable test expressions.

What You'll Learn

  • Test script structure with pm.test
  • Response status code assertions
  • JSON body validation
  • Header and cookie verification
  • Response time assertions

Why It Matters

Test scripts transform manual API exploration into automated validation. They provide immediate feedback on API correctness. Test scripts run in Newman for CI/CD automation.

Real-World Use

All Postman collection runners and monitors use test scripts for pass/fail determination. Stripe's Postman collection includes comprehensive test scripts for payment flows.

flowchart LR
    Request[Send Request] --> Response[Receive Response]
    Response --> TestScript[Test Script]
    TestScript --> Status[Status Checks]
    TestScript --> Body[Body Validation]
    TestScript --> Timing[Timing Checks]
    TestScript --> Headers[Header Checks]
    Status --> Pass/Fail

Teacher Mindset

Write tests that validate what matters for each endpoint. Start with status code. Add body structure validation. Add business logic assertions. Keep tests focused on the API contract.

Code Examples

// Example 1: Basic response assertions
pm.test('Status code is 200', () => {
    pm.response.to.have.status(200);
});

pm.test('Content-Type is JSON', () => {
    pm.response.to.have.header('Content-Type', 'application/json');
});

pm.test('Response time is acceptable', () => {
    pm.expect(pm.response.responseTime).to.be.below(2000);
});

pm.test('Response is an array', () => {
    const body = pm.response.json();
    pm.expect(body).to.be.an('array');
});
// Example 2: Detailed JSON validation
pm.test('User object has required fields', () => {
    const user = pm.response.json();

    pm.expect(user).to.be.an('object');
    pm.expect(user).to.have.property('id');
    pm.expect(user).to.have.property('name');
    pm.expect(user).to.have.property('email');
    pm.expect(user).to.have.property('createdAt');

    pm.expect(user.id).to.be.a('string');
    pm.expect(user.name).to.be.a('string');
    pm.expect(user.email).to.match(/^[\w.-]+@[\w.-]+\.\w+$/);
    pm.expect(user.createdAt).to.match(/^\d{4}-\d{2}-\d{2}T/);
});

pm.test('User has valid role', () => {
    const allowedRoles = ['admin', 'user', 'moderator'];
    pm.expect(pm.response.json().role).to.be.oneOf(allowedRoles);
});
// Example 3: Extracting data for subsequent tests
pm.test('Login returns valid token', () => {
    const body = pm.response.json();

    pm.expect(body).to.have.property('token');
    pm.expect(body.token).to.be.a('string');
    pm.expect(body.token.length).to.be.greaterThan(20);

    // Store for subsequent requests
    pm.environment.set('auth_token', body.token);
    pm.environment.set('user_id', body.user.id);
});

// Conditional tests based on response
if (pm.response.code === 201) {
    pm.test('Created resource has ID', () => {
        pm.expect(pm.response.json()).to.have.property('id');
    });
}

Common Mistakes

  • Writing too many tests that duplicate validation logic
  • Not testing error responses (4xx, 5xx)
  • Using brittle assertions that break on minor data changes
  • Forgetting to parse JSON before accessing properties
  • Not extracting response data for request chaining

Practice

  1. Write a test that checks status code 200 and response time under 1 second.
  2. Write a test that validates JSON body structure and data types.
  3. Write a test that checks response headers.
  4. Extract a token from login response and set it as an environment variable.
  5. Challenge: Write tests for error responses (400, 401, 404, 500) with appropriate error message validation.

FAQ

What assertion library does Postman use?

Postman uses Chai for assertions. The pm.expect() syntax is based on Chai's expect style.

Can I run tests without viewing the response?

Yes. Tests run automatically and show pass/fail results. Failed tests include the assertion error message.

How do I test array responses?

Use pm.expect(body).to.be.an('array') and iterate with forEach or access by index.

Can I test GraphQL responses?

Yes. Parse the response as JSON and access the data or errors property.

How do I skip tests conditionally?

Wrap test code in if statements. Use pm.expect.skip() for conditional skipping.

Mini Project

Write test scripts for a CRUD collection: GET list (array validation), GET by ID (object structure), POST (created status, returned ID), PUT (updated fields), DELETE (success status, verify deletion with follow-up GET), and error cases (404, 422 validation).

What's Next

Next, you will learn about assertions using pm.expect and the Chai library.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro