</>

Technology

Postman

Difficulty

Intermediate

Interview Question

What is the difference between Pre-request Scripts and Tests in Postman?

Answer

Pre-request Scripts vs Tests in Postman

Both are JavaScript tabs in Postman, but they run at different times and serve different purposes.

Pre-request Scripts

Run BEFORE the request is sent. Used for setup and preparation.

Use Cases

  • Generate dynamic values (timestamps, random data)
  • Set authentication tokens
  • Calculate checksums or signatures
  • Chain requests by using data from a previous response

Examples

JavaScript
// Generate a random email
const randomEmail = `user_${Date.now()}@test.com`;
pm.environment.set("random_email", randomEmail);

// Get current timestamp
pm.environment.set("timestamp", new Date().toISOString());

// Fetch a token before the actual request (via pm.sendRequest)
pm.sendRequest({
    url: pm.environment.get("base_url") + "/auth/login",
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
        mode: "raw",
        raw: JSON.stringify({ username: "admin", password: "secret" })
    }
}, function (err, res) {
    pm.environment.set("auth_token", res.json().token);
});

Tests (Post-response Scripts)

Run AFTER the response is received. Used for validation.

Use Cases

  • Assert status codes
  • Validate response body fields
  • Check response headers
  • Save values from response for next request
  • Log debugging info

Examples

JavaScript
pm.test("Status is 201", function () {
    pm.response.to.have.status(201);
});

const json = pm.response.json();
pm.test("Name matches", function () {
    pm.expect(json.name).to.eql(pm.environment.get("random_name"));
});

// Save for next request
pm.environment.set("created_id", json.id);

Summary

FeaturePre-request ScriptTests (Post-response)
RunsBefore requestAfter response
PurposeSetup / PreparationValidation / Assertions
Access to responseNoYes
Common useToken generation, dynamic dataStatus code checks, body validation

Follow AutomateQA

Related Topics