⚡ Programmable Automation via Postman's JavaScript Runtime Sandbox
Postman embeds a secure Node.js execution sandbox that executes arbitrary JavaScript before a request hits the wire (Pre-request Script) and immediately after the response stream returns (Tests Script). Rather than relying on static mock inputs, pre-request scripts enable dynamic payload generation, timestamp hashing, automated header injection, and cryptographic request signing. Conversely, test scripts transform Postman into a robust test automation framework using the Chai BDD assertion library (pm.expect), Ajv/tv4 JSON Schema validators, and asynchronous orchestration via pm.sendRequest(). Mastering these scripts allows quality engineers to build self-healing regression suites, assert complex business invariants, and decouple authentication handshakes across enterprise microservices.
POSTMAN SANDBOX EXECUTION PIPELINE:
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ 1. PRE-REQUEST SCRIPT (Runs BEFORE HTTP dispatch) │
│ * Injects dynamic headers, hashes signatures, sets ephemeral variables │
│ * Built-in libraries available: lodash (_), crypto-js (CryptoJS), moment (dates), cheerio │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ 2. HTTP NETWORK TRANSACTION (Dispatched to target server over wire) │
│ * Resolves {{variables}} inside URL, Headers, and JSON body templates │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ 3. TESTS SCRIPT (Runs AFTER response bytes are received) │
│ * Evaluates HTTP status, headers, latency SLA, response time, and payload body │
│ * Built-in assertion engine: Chai.js BDD (pm.test, pm.expect), Ajv Schema Validator │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
CORE SANDBOX OBJECTS & MODULES:
* pm.request : Read/mutate request headers, URL parameters, method, and raw body
* pm.response : Read status code, response time, response size, headers, and parsed JSON/XML
* pm.variables : Get/set values across local, data, environment, and collection scopes
* pm.test() : Encapsulates assertion blocks; logs test passes and failures in the UI runner
* pm.expect() : Chai BDD assertion syntax: pm.expect(actual).to.be.oneOf([200, 201])
* pm.sendRequest : Asynchronously dispatch sub-requests from inside scripts without altering UI flow
* CryptoJS : Cryptographic hashing: SHA256, HMAC, MD5, AES, Base64 encoding/decoding
* _ (Lodash) : Functional data manipulation: _.chunk, _.find, _.groupBy, _.isEqual
// 1. Generate unique dynamic attributes
const timestamp = Math.floor(Date.now() / 1000);
const nonce = "NONCE-" + Math.random().toString(36).substring(2, 10).toUpperCase();
const uniqueEmail = `test.student.${timestamp}@nikita-infotech.com`;
// Set local variables for dynamic resolution in Request Body: {{dynamic_email}}
pm.variables.set("dynamic_email", uniqueEmail);
pm.variables.set("request_timestamp", timestamp.toString());
pm.variables.set("request_nonce", nonce);
// 2. Cryptographic HMAC-SHA256 Request Signing
const apiSecretKey = pm.environment.get("api_secret_key") || "TEST_SECRET_KEY_99214";
const requestPayload = JSON.stringify({
studentEmail: uniqueEmail,
courseCode: "API-TESTING-PRO",
timestamp: timestamp
});
// Construct canonical signing string: METHOD + TIMESTAMP + NONCE + PAYLOAD
const canonicalString = `POST\n${timestamp}\n${nonce}\n${requestPayload}`;
// Generate HMAC-SHA256 hash using built-in CryptoJS
const hmacSignature = CryptoJS.HmacSHA256(canonicalString, apiSecretKey).toString(CryptoJS.enc.Hex);
// Inject calculated signature directly into request headers before transmission!
pm.request.headers.upsert({
key: "X-Signature",
value: hmacSignature
});
pm.request.headers.upsert({
key: "X-Timestamp",
value: timestamp.toString()
});
console.log("[+] Pre-request script generated HMAC Signature:", hmacSignature);
pm.test() and pm.expect().
// 1. Assert Status Code conformances
pm.test("Status code is 201 Created", function () {
pm.response.to.have.status(201);
});
pm.test("Status code is one of the valid successful codes", function () {
pm.expect(pm.response.code).to.be.oneOf([200, 201, 204]);
});
pm.test("Status code name has expected HTTP string", function () {
pm.response.to.have.status("Created");
});
// 2. Performance SLA & Latency Assertions
pm.test("Response time is within enterprise SLA threshold (< 600ms)", function () {
pm.expect(pm.response.responseTime).to.be.below(600);
});
// 3. Response Header Assertions
pm.test("Content-Type is UTF-8 encoded application/json", function () {
pm.response.to.have.header("Content-Type");
pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});
pm.test("Security and tracing headers are present", function () {
pm.response.to.have.header("X-Request-Id");
pm.response.to.have.header("Strict-Transport-Security");
});
// Parse the incoming JSON body
const responseBody = pm.response.json();
pm.test("Validate student profile root schema attributes", function () {
pm.expect(responseBody).to.be.an("object");
pm.expect(responseBody).to.have.all.keys(
"studentId", "fullName", "email", "enrolledCourses", "accountStatus", "metadata"
);
});
pm.test("Assert primitive data types and formats", function () {
// Assert ID adheres to expected regex pattern (e.g., STU- followed by 5 digits)
pm.expect(responseBody.studentId).to.match(/^STU-[0-9]{5}$/);
// Assert email structure
pm.expect(responseBody.email).to.include("@nikita-infotech.com");
// Assert boolean and enum states
pm.expect(responseBody.accountStatus).to.be.oneOf(["ACTIVE", "PENDING_VERIFICATION"]);
pm.expect(responseBody.metadata.isEmailVerified).to.be.a("boolean").that.is.true;
});
pm.test("Assert nested array structures and contents", function () {
const courses = responseBody.enrolledCourses;
pm.expect(courses).to.be.an("array").that.is.not.empty;
pm.expect(courses.length).to.be.at.least(1);
// Use Lodash to locate a specific course object inside array
const targetCourse = _.find(courses, { courseCode: "API-TESTING-PRO" });
pm.expect(targetCourse, "Course 'API-TESTING-PRO' must exist").to.not.be.undefined;
pm.expect(targetCourse.credits).to.be.a("number").and.to.eql(4);
});
pm.expect() statements for dozens of fields, validate the entire response structure against a strict JSON Schema definition in a single automated test.
// 1. Define formal JSON Schema
const studentSchema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["studentId", "fullName", "email", "accountStatus"],
"properties": {
"studentId": {
"type": "string",
"pattern": "^STU-[0-9]{5}$"
},
"fullName": {
"type": "string",
"minLength": 3,
"maxLength": 60
},
"email": {
"type": "string",
"format": "email"
},
"accountStatus": {
"type": "string",
"enum": ["ACTIVE", "INACTIVE", "SUSPENDED"]
},
"gpa": {
"type": "number",
"minimum": 0.0,
"maximum": 4.0
}
},
"additionalProperties": false
};
// 2. Validate response against schema using tv4 or Ajv
pm.test("Response body strictly adheres to JSON Schema contract", function () {
// Option A: Using Postman's built-in tv4 validator
const validationResult = tv4.validateResult(pm.response.json(), studentSchema);
if (!validationResult.valid) {
console.error("Schema Violation Details:", validationResult.error);
}
pm.expect(validationResult.valid,
`Schema Error: ${validationResult.error ? validationResult.error.message : ''}`
).to.be.true;
});
// Check if cached token exists and has not expired
const existingToken = pm.environment.get("access_token");
const tokenExpiry = Number(pm.environment.get("token_expiry_timestamp") || 0);
const now = Math.floor(Date.now() / 1000);
if (!existingToken || now >= tokenExpiry) {
console.log("[*] Access token missing or expired. Requesting fresh OAuth token...");
// Construct asynchronous OAuth token request payload
const tokenRequestDetails = {
url: pm.environment.get("auth_server_url") || "https://auth.nikita-infotech.com/oauth/token",
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: {
mode: "urlencoded",
urlencoded: [
{ key: "grant_type", value: "client_credentials" },
{ key: "client_id", value: pm.environment.get("client_id") || "qa_runner" },
{ key: "client_secret", value: pm.environment.get("client_secret") || "sec_991823" }
]
}
};
// Dispatch asynchronous call before continuing with primary request
pm.sendRequest(tokenRequestDetails, function (err, res) {
if (err) {
console.error("Failed to acquire OAuth token:", err);
return;
}
const data = res.json();
pm.environment.set("access_token", data.access_token);
pm.environment.set("token_expiry_timestamp", now + data.expires_in - 60);
console.log("[+] Fresh token acquired and saved to environment successfully!");
});
} else {
console.log("[+] Using valid cached OAuth token. Skipping auth sub-request.");
}
// 1. Verify successful resource creation
pm.test("Resource creation succeeded (HTTP 201)", function () {
pm.response.to.have.status(201);
});
// 2. Extract generated unique identifier from response
const responseData = pm.response.json();
const generatedStudentId = responseData.studentId;
const createdRecordLocation = pm.response.headers.get("Location");
pm.test("Verify primary key was generated", function () {
pm.expect(generatedStudentId).to.be.a("string").that.is.not.empty;
});
// 3. Persist state across the Collection Runner lifecycle
pm.environment.set("active_student_id", generatedStudentId);
pm.environment.set("resource_location_url", createdRecordLocation);
console.log(`[+] State Saved: active_student_id = ${generatedStudentId}`);
// Downstream requests can now call: GET {{base_url}}/api/v1/students/{{active_student_id}}
xml2Json.
// 1. Parse XML response into structured JavaScript object
const xmlData = pm.response.text();
const jsonObject = xml2Json(xmlData);
pm.test("SOAP Envelope contains valid Body element", function () {
pm.expect(jsonObject).to.have.property("soap:Envelope");
pm.expect(jsonObject["soap:Envelope"]).to.have.property("soap:Body");
});
pm.test("Assert XML student enrollment attributes", function () {
const studentNode = jsonObject["soap:Envelope"]["soap:Body"]["StudentResponse"];
// Assert XML attribute values
pm.expect(studentNode["_id"]).to.eql("STU-99214");
// Assert text elements inside XML tags
pm.expect(studentNode["FullName"]).to.eql("Nikita Sharma");
pm.expect(studentNode["EnrollmentStatus"]).to.eql("CONFIRMED");
pm.expect(Number(studentNode["Credits"])).to.be.at.least(1);
});
postman.setNextRequest().
const responseBody = pm.response.json();
const currentStatus = responseBody.status;
let retryCount = Number(pm.environment.get("async_poll_count") || 0);
const MAX_RETRIES = 5;
if (currentStatus === "IN_PROGRESS" || currentStatus === "PENDING") {
if (retryCount < MAX_RETRIES) {
console.log(`[*] Job still in progress. Polling retry #${retryCount + 1}...`);
// Increment retry counter in environment
pm.environment.set("async_poll_count", retryCount + 1);
// Instruct runner to repeat the CURRENT request!
postman.setNextRequest(pm.info.requestName);
} else {
pm.test("Async Job SLA Timed Out", function () {
pm.expect.fail(`Job failed to finish within ${MAX_RETRIES} polling attempts.`);
});
// Jump directly to cleanup request, skipping intermediate tests
postman.setNextRequest("Tear Down Mock Data");
}
} else if (currentStatus === "COMPLETED") {
console.log("[+] Asynchronous job finished successfully! Proceeding to verification.");
pm.environment.unset("async_poll_count"); // Reset counter
// Proceed to next logical step
postman.setNextRequest("Verify Processed Output");
} else {
// Unhandled or failed terminal status
postman.setNextRequest(null); // STOPS collection execution immediately!
}
POSTMAN CHAI BDD ASSERTION SYNTAX CHEAT SHEET:
┌──────────────────────────────┬────────────────────────────────────────────────────────────────────────┐
│ ASSERTION INTENT │ CHAI BDD SCRIPT SYNTAX │
├──────────────────────────────┼────────────────────────────────────────────────────────────────────────┤
│ Exact Value Equality │ pm.expect(data.status).to.eql("SUCCESS"); │
│ Numeric Boundaries │ pm.expect(data.credits).to.be.at.least(1).and.at.most(6); │
│ Floating Point Tolerance │ pm.expect(data.taxRate).to.be.closeTo(0.18, 0.001); │
│ Type Verification │ pm.expect(data.isActive).to.be.a("boolean"); │
│ Object Property Existence │ pm.expect(data).to.have.property("studentId"); │
│ Array Membership │ pm.expect(data.roles).to.include("ROLE_ADMIN"); │
│ Array Non-Empty Check │ pm.expect(data.items).to.be.an("array").that.is.not.empty; │
│ String Regex Match │ pm.expect(data.zipCode).to.match(/^[0-9]{6}$/); │
│ Header Presence │ pm.response.to.have.header("Content-Type"); │
│ Performance SLA Check │ pm.expect(pm.response.responseTime).to.be.below(500); │
├──────────────────────────────┴────────────────────────────────────────────────────────────────────────┤
│ TOP 5 POSTMAN SCRIPTING BEST PRACTICES: │
│ 1. Wrap assertions in pm.test(): Uncaught assertions outside pm.test() halt the entire runner script. │
│ 2. Provide custom failure messages: pm.expect(val, "Failed asserting user tier").to.eql("GOLD"); │
│ 3. Fail-fast on 500 errors: Check status code first before attempting to parse pm.response.json(). │
│ 4. Clear environment variables after test runs: Prevent dirty data leaks across consecutive runs. │
│ 5. Use console.log() for debugging: Inspect variables in the Postman Console (Ctrl+Alt+C / Cmd+Alt+C).│
└───────────────────────────────────────────────────────────────────────────────────────────────────────┘