Writing Postman Tests and Scripts

Postman is more than a request sender; it also includes a lightweight scripting environment based on JavaScript. Tests and pre-request scripts let you automate checks, chain requests together, and prepare dynamic data. This turns collections into powerful mini test suites.

Postman Tests and the pm API

Postman tests run after a response is received. They use the pm API, which exposes the request, response, and environment context. You can write assertions on status codes, headers, and JSON fields. These tests then show as pass or fail in the Postman UI and in Newman runs.

// Example Postman test script

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

pm.test("Customer has expected email", function () {
  const json = pm.response.json();
  pm.expect(json.email).to.eql("alice@example.com");
});
Note: Tests are written per request, but you can also define common scripts at collection or folder level to avoid repetition.
Tip: Start by automating simple assertions such as status and key fields, then gradually add more complex checks as your understanding grows.
Warning: Overloading a single request with dozens of assertions can make failures hard to interpret. Keep tests focused and readable.

Pre-request scripts run before a request is sent. They are often used to compute values, set headers, or update variables dynamically. For example, you might generate a timestamp, sign a request, or fetch an auth token from another source.

Chaining Requests with Scripts

By combining tests and pre-request scripts, you can create flows where one request stores data (like an ID or token) as a variable, and subsequent requests reuse it. This mimics user journeys and reduces manual copying of values between steps.

Common Mistakes

Mistake 1 โ€” Not using tests at all

Without tests, you rely on manual inspection every time.

โŒ Wrong: Only eyeballing responses instead of asserting expectations.

โœ… Correct: Add at least basic automated checks to each important request.

Mistake 2 โ€” Putting all logic in a single complex script

Large scripts are fragile and hard to debug.

โŒ Wrong: One script that handles many unrelated concerns.

โœ… Correct: Keep scripts small, purposeful, and reuse them through collection-level definitions.

🧠 Test Yourself

What is the main benefit of writing Postman tests?