3 / 65 · 14 API Testing Fundamentals · Postman Exploration← prev⊞ allnext →☰ Read as one page
1.3Writing Test Scripts
Postman's test scripts run after each request, validating responses inline.
Basic Assertions
// Status code
pm.test("Status is 200", () => {
pm.response.to.have.status(200);
});
// Response has expected fields
pm.test("Response has user ID", () => {
const data = pm.response.json();
pm.expect(data.id).to.be.a("number");
pm.expect(data.email).to.be.a("string");
pm.expect(data).to.not.have.property("password");
});
// Response time
pm.test("Response time < 500ms", () => {
pm.expect(pm.response.responseTime).to.be.below(500);
});
// Headers
pm.test("Content-Type is JSON", () => {
pm.response.to.have.header("Content-Type", "application/json; charset=utf-8");
});
Chaining Requests
Extract data from one request and use it in the next:
// In POST /auth/login Tests tab:
pm.test("Save auth token", () => {
const token = pm.response.json().access_token;
pm.environment.set("auth_token", token);
});
// In subsequent requests, use {{auth_token}} in the Authorization header:
// Bearer {{auth_token}}
Dynamic Variables
Postman provides built-in dynamic variables:
{{$randomEmail}} -> random email address
{{$randomFullName}} -> random name
{{$randomUUID}} -> UUID v4
{{$timestamp}} -> current Unix timestamp
{{$randomInt}} -> random integer