Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 30 ยท Writing Tests and Scripts

Writing tests with pm.test and Chai

Write Postman tests with pm.test and pm.expect: check status codes, JSON bodies, headers and response time, validate a JSON schema, and read the Test Results tab.

Sending a request and looking at the answer with your own eyes is exploring. Turning your expectations into code that Postman checks automatically, every time, is testing. A Postman test is a small JavaScript function in the Tests tab (also called Post-response in newer versions) that runs after the response arrives and reports pass or fail for each thing you claimed.

You write tests with two ideas: pm.test() to name and group a check, and pm.expect() (the Chai assertion library) to say what should be true. In this lesson you learn the everyday assertions for status codes, JSON, headers and timing, how schema validation fits in, and how to read the results. The real Postman sandbox cannot run here, so the Postman code is read-only; the runnable stand-in is a small test runner in plain JavaScript that follows the same style.

Anatomy of a test

Name Says what should be true.
Function Holds one or more assertions.
Assertion pm.expect(actual).to...

If any assertion throws, that test fails.

1 / 2

Your first tests

Open a request, go to the Tests tab, and write:

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

pm.test("Response is JSON with an id", function () {
  const body = pm.response.json();
  pm.expect(body).to.have.property("id");
  pm.expect(body.id).to.be.a("number");
});

Send the request. The Test Results tab of the response lists each test with PASS or FAIL, and a failure shows the message of the assertion that threw. Tests do not stop each other: if the first fails, the second still runs, so one run shows you everything that is wrong, not only the first problem.

A test is just a function; arrow functions work too. An assertion that fails throws an error, and pm.test catches it and records a failure. Code outside any pm.test that throws is a script error, not a failed test, so keep your checks inside pm.test.

Reading the response

These are the pieces of the response you will check most:

JavaScript
pm.response.code                         // 200 (the number)
pm.response.status                       // "OK"
pm.response.json()                       // parsed JSON body
pm.response.text()                       // body as text
pm.response.headers.get("Content-Type")  // one header (case-insensitive)
pm.response.responseTime                 // milliseconds
pm.response.responseSize                 // bytes

Shortcuts exist for common cases: pm.response.to.have.status(201), pm.response.to.be.ok (any 2xx), pm.response.to.have.header("Content-Type") and pm.response.to.be.json. They read well and produce good failure messages, so use them where they fit.

The Chai assertions you need

pm.expect() uses the Chai BDD style: a chain of readable words that do nothing (to, be, have, that, and) leading to a real assertion. A few dozen words cover most real tests:

Assertion Meaning
.to.equal(x) strictly equal (===)
.to.eql(x) deep equality for objects and arrays
.to.be.a("string") type check ("number", "array", "object", "boolean")
.to.include("sale") string contains, or array contains
.to.have.property("id") object has the key (optionally with a value)
.to.have.lengthOf(3) array or string length
.to.be.above(0) / .below(200) numeric comparison
.to.match(/^ORD-\d+$/) regular expression
.to.be.ok / .to.be.true truthy / exactly true
.to.not... negate the whole assertion

Note the difference between equal and eql: pm.expect([1, 2]).to.equal([1, 2]) fails because two arrays are two different objects, while eql compares their contents.

Typical API checks

Putting these together, a realistic test script for POST /products looks like this (read-only; it needs a real server):

JavaScript
pm.test("201 Created", () => pm.response.to.have.status(201));

pm.test("Content-Type is JSON", () => {
  pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});

pm.test("Product has the expected shape", () => {
  const product = pm.response.json();
  pm.expect(product.id).to.be.a("number");
  pm.expect(product.name).to.equal("Widget");
  pm.expect(product.price).to.be.above(0);
  pm.expect(product.tags).to.include("new");
});

pm.test("No sensitive fields leak", () => {
  pm.expect(pm.response.json()).to.not.have.property("internalCost");
});

pm.test("Responds within 500 ms", () => {
  pm.expect(pm.response.responseTime).to.be.below(500);
});

Good habits visible here: one idea per test, names that read as sentences, assertions on meaning (a price above zero) rather than on exact volatile values (a timestamp), and at least one negative check for things that must not be there.

Schema validation

Checking five fields by hand is fine; checking fifty is tedious. A JSON Schema describes the expected shape once (required keys, types, allowed values), and Postman can validate a response against it. In Postman's sandbox this is commonly done with the built-in ajv library or the older tv4, or with pm.response.to.have.jsonSchema(schema). A sketch:

JavaScript
const schema = {
  type: "object",
  required: ["id", "name", "price"],
  properties: {
    id: { type: "integer" },
    name: { type: "string" },
    price: { type: "number", minimum: 0 },
  },
};

pm.test("Body matches the schema", () => {
  pm.response.to.have.jsonSchema(schema);
});

Schemas catch a type that silently changed from number to string, which hand-written spot checks often miss. See Contract testing and OpenAPI for the full picture. The second stand-in below implements a very small schema check so you can see what a validator does.

A mini test runner

The stand-in implements pm.test and a Chai-like pm.expect with the assertions from the table, and runs a set of tests against a fake response. One test is written to fail on purpose, so you can see a failure report and notice that later tests still run. The stand-in uses JSON.stringify for deep equality; real Chai is more thorough.

JS A mini pm.test and pm.expect runner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The report format mirrors the Test Results tab: one line per test, failures with their message, and a total. Notice that the failed price test did not prevent the tests after it from running.

What a schema validator does

Here is a deliberately small validator handling type, required, properties and minimum, so the idea of "shape checking" is concrete. Real validators such as Ajv support far more keywords.

JS A very small JSON Schema check

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The bad object has a string id, a negative price and no name; the validator reports all three, which is exactly what makes schema tests catch type drift.

Tips for dependable tests

  • Test one behaviour per pm.test and name it like a sentence.
  • Avoid brittle values: do not assert exact timestamps or generated ids; assert their type or format.
  • Check the failure paths too: wrong input should give a 4xx with a useful error body (see API testing strategy and test design).
  • Put shared checks at the collection level (status is not 5xx, response time budget).
  • Use variables from earlier steps instead of hard-coding ids (see Chaining requests and workflows).
  • When parsing JSON, guard against a non-JSON body (an HTML error page), because pm.response.json() throws in that case and the error hides the real problem.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A request has three pm.test blocks and the first one fails. What happens to the others?

    Each pm.test catches its own failures, so one run reports every problem.
  2. 2. What is the difference between to.equal and to.eql in Chai?

    Two distinct arrays are never === each other, so use eql when you want to compare their contents.
  3. 3. Which test is the most dependable?

    Formats and types are stable; exact generated or time-dependent values change on every run.
  4. 4. What does a JSON Schema check catch that a few hand-picked assertions often miss?

    A schema describes the full shape, so type changes and missing fields are reported even if you never wrote an assertion for them.
  5. 5. Where should a check that every response is below 1000 ms be written?

    A collection-level script runs after every request, so the rule is written once.

Summary

  • pm.test(name, fn) groups checks; a thrown assertion marks that test failed and the others still run.
  • pm.expect(actual).to... is Chai BDD style: equal, eql, a, include, property, above, below, match, not.
  • Read the response with pm.response.code, .json(), .headers.get() and .responseTime.
  • Schemas validate the whole shape of a body; use ajv or jsonSchema in Postman.
  • Prefer stable, meaningful assertions, include negative checks, and share common ones at collection level.

Next: connect requests into a workflow with Chaining requests and workflows.