T10 Postman · Lesson 4
Tests in Postman
An answer is not a good answer until something checks it. Write tests with pm.test and pm.expect, check a response's status, headers and JSON, read Chai's messages when a check fails, find every failure in Newman's summary, and let the exit code stop a build.
- write a test with pm.test, and say exactly when it passes and when it fails
- check values with pm.expect and Chai: equal, eql, a, include, property, lengthOf, above, below, oneOf and not
- check a response's status, headers and JSON body with pm.response.to.have and pm.response.to.be
- read a failed check's message and find it in Newman's summary, with its item and its place in the script
- use the exit code of newman run to stop a build when a test fails
- avoid tests that cannot fail, such as one that returns false instead of throwing
The back cover
A runner that brings back answers is only half a helper. Somebody still has to read every answer, every morning. And on the busiest morning of all, somebody always misses the one answer that matters.
These pages teach the box to check its own answers. They write tests with pm.test, describe what each value should be with pm.expect, and check a response's status, headers and body. They read the messages a failed check leaves, find every failure in the summary, and let one failure stop a build through the exit code.
Before you start
The story: Answers nobody read
The runner now carries the box to both yards every morning and comes back with a heap of answers. The clerks glance at the first few and file the rest. One morning the boiler's reading comes back as a word instead of a number, and nobody notices for a week.
Another day the yard answers every question with a polite page that says it is closed for repairs. Every card was answered, so the report looks fine.
Postmaster Meera Franking takes a red pen to the cards. "An answer is not a good answer," she says. "Under every question, write what the answer must say: its number, its kind, its fields. Let the runner check each one and tell me only what failed. And if anything failed, the report must say so on its cover."
Lessons 01 to 03 sent requests, organised them and fed them values. A run printed what came back, and you read it. That works for three requests on a quiet afternoon. It fails on a busy morning with three hundred, and it fails at night, when a build server runs the collection and nobody is watching at all.
A test is a check written down, so that the machine reads the answer for you: the status must be 200, the body must be JSON, the value must be a number above zero. This lesson writes tests with pm.test and pm.expect, checks a response's status, headers and body, reads the messages a failed check leaves, and lets one failure stop a build.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| A first test. | pm.test("status is 200", ...) | This whole lesson. |
| The assertion event. | .on("assertion", ...) | Seeing each test pass or fail. |
| The summary. | summary.run.failures | Every failure, in detail. |
| Throwing errors. | throw new Error("...") | How a test fails. |
| Functions as arguments. | () => ... | The check inside pm.test. |
| JSON and its types. | { "value": 95 } | Checking fields and types. |
| Arrays and their length. | [1, 2].length | Checking a list. |
| Headers. | Content-Type: application/json | Checking a header. |
| Status codes. | 200, 201, 400, 404 | Checking the status. |
| The exit code. | exit: 1 | Stopping a build. |
By the end of this lesson you will be able to:
- write a test with pm.test, and say exactly when it passes and when it fails;
- check values with pm.expect and Chai: equal, eql, a, include, property, lengthOf, above, below, oneOf and not;
- check a response's status, headers and JSON body with pm.response.to.have and pm.response.to.be;
- read a failed check's message and find it in Newman's summary, with its item and its place in the script;
- use the exit code of newman run to stop a build when a test fails;
- avoid tests that cannot fail, such as one that returns false instead of throwing.
How to follow this lesson
As before, every block is one program: it starts the gauges server, runs a collection with Newman's library and prints what each test said. The small Newman on this page has a small copy of Chai, the library behind pm.expect, whose messages were measured against the real Chai inside Newman 6.2.3, word for word.
Every block has also been run with the real Newman, where it prints the same, failures and messages included.
In one line
A test is a check written down: pm.test names it, pm.expect or pm.response.to checks the answer, a failed check throws and leaves a message, and Newman's summary and exit code tell everyone what failed.
What a test is
At a glance
A test is a check written down, so that a machine can read every answer for you.
pm.test takes a name and a function. Newman runs the function: if it finishes, the test passes, and if it throws, the test fails, with the error's message. What the function returns does not matter, so a test that returns false still passes. Tests are numbered from 0 in the order they are called, pm.test.skip reports a test as skipped, and a test that takes done waits for it.
Take a guess: Why do testing tools ask you to give every test a name written as a sentence?
You met pm.test in lesson 01. Now look at it closely, because everything else in this lesson sits inside it. A test has two parts: a name, which is what reports show, and a function, which does the checking. Newman runs the function. If it finishes, the test passed. If it throws an error, the test failed, and the error's message becomes the test's message.
Here are three tests on the boiler's answer. The server is the gauges server once more, this time keeping its gauges in a list, so that later tests can check arrays and fields:
server.js
const express = require("express");
const app = express();
app.use(express.json());
const gauges = [
{ name: "boiler", value: 95, unit: "C" },
{ name: "pump", value: 40, unit: "bar" },
];
app.get("/gauges", (req, res) => res.json(gauges));
app.get("/gauges/:name", (req, res) => {
const gauge = gauges.find((g) => g.name === req.params.name);
if (!gauge) return res.status(404).json({ error: "no such gauge" });
res.json(gauge);
});
app.post("/gauges", (req, res) => {
if (typeof req.body?.value !== "number") return res.status(400).json({ error: "value must be a number" });
gauges.push(req.body);
res.status(201).json(req.body);
});
module.exports = app;
app.js
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "read the boiler",
request: "http://localhost:3000/gauges/boiler",
event: [{ listen: "test", script: { exec: [
'pm.test("answers 200", () => pm.response.to.have.status(200));',
'pm.test("is the boiler", () => pm.expect(pm.response.json().name).to.equal("boiler"));',
'pm.test("reads above 100", () => pm.expect(pm.response.json().value).to.be.above(100));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✓ answers 200
✓ is the boiler
✗ reads above 100 | expected 95 to be above 100
The first two checks held, so their functions finished: two ticks. The third check, pm.expect(95).to.be.above(100), did not hold, so pm.expect threw an error, and the test failed with the error's message: expected 95 to be above 100. That message was written by Chai, the library behind pm.expect, and it says exactly what was wrong.
In the app, tests go in the request's Scripts tab, under Post-response, and the Snippets list at the lower right of the editor writes common ones for you. After Send, the response pane's Test Results tab shows how many passed, out of how many ran.
A checklist with a red pen
A test is one line of a checklist: the name says what is checked, and the function holds the red pen. If the pen never moves, the line is ticked. The moment the pen has to write, the line is crossed out, and what it writes is the reason.
Only a throw fails a test
Here is the most important rule of this section, and the most common mistake with it. Postman's own page describes the function as returning true or false. Measured with Newman 6.2.3, the value a function returns is ignored: a test fails only when its function throws.
Worked example 1
Three tests on an answer whose status is 200: one returns false, one returns a comparison that is false, and one uses pm.expect. Which of them fail?
What we have: the boiler's answer, status 200, and three tests that each say, one way or another, that the status should be 404
What we need: which tests pass and which fail
The plan: run them, and remember that only a throw fails a test
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "read the boiler",
request: "http://localhost:3000/gauges/boiler",
event: [{ listen: "test", script: { exec: [
'pm.test("returns false", () => false);',
'pm.test("returns a comparison", () => pm.response.code === 404);',
'pm.test("expects 404", () => pm.expect(pm.response.code).to.equal(404));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✓ returns false
✓ returns a comparison
✗ expects 404 | expected 200 to equal 404
- The first function returned false and the second returned a false comparison, but neither threw, so both passed.
- Only the third, written with pm.expect, threw when the status was not 404, so only it failed.
Only expects 404 fails. The other two pass even though what they return is false.
Check: The status really is 200, so all three should have failed; only the one that throws did.
A path that fails: writing tests as comparisons, () => pm.response.code === 404. They read well, they always pass, and they hide every fault they were written to catch.
So every check inside a test should be one that throws when it fails. pm.expect throws, and so does pm.response.to, as the next sections show. If you write your own check, throw an Error yourself.
Several tests, skipped tests, and their numbers
A script may hold many tests, and each passes or fails on its own: one failure does not stop the next test. Newman numbers them in the order pm.test is called, from 0, and a failure records its number as assertion:N in test-script. A test that is not ready yet can be written with pm.test.skip: it is reported as skipped and never run, but it still counts, and it still takes its number.
Worked example 2
Write a test that passes, a test that is not ready yet, and a test that fails, and find the failing one's number.
What we have: three tests: first passes, second is skipped, third throws an error of its own
What we need: how each test is reported, and where the failure is recorded
The plan: use pm.test.skip for the second, read args.skipped in the assertion event, and print each failure's at
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "read the boiler",
request: "http://localhost:3000/gauges/boiler",
event: [{ listen: "test", script: { exec: [
'pm.test("first", () => {});',
'pm.test.skip("second, not ready yet", () => {});',
'pm.test("third", () => { throw new Error("broken on purpose"); });',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, (err, summary) => {
for (const failure of summary.run.failures) console.log("the failure is at", failure.at);
server.close();
}).on("assertion", (err, args) => console.log(args.assertion, "|", args.skipped ? "skipped" : err ? err.message : "passed"));
});
Terminal: node app.js
first | passed
second, not ready yet | skipped
third | broken on purpose
the failure is at assertion:2 in test-script
- The skipped test was reported as skipped; its function never ran.
- The failure is at assertion:2: first was 0, the skipped one was 1, and third was 2. A skipped test still takes its number.
first passes, second is skipped, third fails, and its failure is at assertion:2 in test-script.
Check: Three calls of pm.test, numbered 0, 1 and 2.
Another way: throw your own error, as third did, when no ready-made check fits: its message becomes the test's message.
Most tests check at once. A test whose function takes a parameter, usually called done, is one that waits: Newman waits for it to call done before it moves on, and calling done(error) fails it. Its result arrives when done is called, so it can come after the tests below it:
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "read the boiler",
request: "http://localhost:3000/gauges/boiler",
event: [{ listen: "test", script: { exec: [
'pm.test("checked later", (done) => {',
' setTimeout(() => { pm.expect(pm.response.json().unit).to.equal("C"); done(); }, 10);',
'});',
'pm.test("checked at once", () => pm.response.to.have.status(200));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✓ checked at once
✓ checked later
When you are stuck: A test passes when it should fail
Does its function throw when the check fails? A returned false is ignored.
Is the check inside the function? pm.test("x", pm.response.code === 200) passes a true or false instead of a function, and passes every time.
Was it skipped? pm.test.skip never runs its function.
Your turn
A test's function returns false and throws nothing. Does the test pass or fail?Tap to reveal
- What makes a test fail?
It passes: only a throw fails a test.
A script calls pm.test three times; the second call is pm.test.skip. If the third test fails, what is its number in the failure's at?Tap to reveal
- Tests are numbered from 0, in the order they are called.
- A skipped test still takes a number.
assertion:2 in test-script.
cat > app.js <<'END'
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "read the boiler",
request: "http://localhost:3000/gauges/boiler",
event: [{ listen: "test", script: { exec: [
'pm.test("named boiler", () => pm.expect(pm.response.json().name).to.equal("boiler"));',
'pm.test("in bar", () => pm.expect(pm.response.json().unit).to.equal("bar"));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
✓ named boiler
✗ in bar | expected 'C' to equal 'bar'
- The boiler is named boiler, so the first check holds.
- Its unit is C, not bar, so pm.expect throws.
It prints ✓ named boiler, then ✗ in bar | expected 'C' to equal 'bar'.
Did you know?
Names that read as sentences
Test names written as sentences come from BDD, behaviour-driven development. Dan North introduced it in an article of 20 September 2006, which begins: I had a problem. Programmers he taught kept asking where to start, what to test, what to call their tests and how to understand why a test fails. His first answer was that test method names should be sentences.
Why it fits here: It answers this topic's question: naming tests as sentences came from Dan North's BDD, to make a failing test explain itself.
Source: Dan North: Introducing BDD
Where API tests sit in the pyramid
Teams often picture their tests as a pyramid. Martin Fowler writes that most people know the test pyramid from Mike Cohn, who described it in his 2009 book Succeeding with Agile. Its point, in Fowler's words, is that you should have many more low-level unit tests than high-level tests that run through a screen; API tests like this lesson's sit in the middle.
Why it fits here: It places this topic's tests: API tests sit between many small unit tests and a few slow tests through the screen.
Source: Martin Fowler: TestPyramid
In one line
pm.test runs a named function: it passes if the function finishes and fails if it throws, whatever it returns; tests are numbered from 0 in the order they are called, and pm.test.skip reports a test as skipped without running it.
Checking values with pm.expect
At a glance
pm.expect describes what a value should be, in words joined by dots.
It is Chai's expect. Words such as to, be and have only make the line read well; words such as a, lengthOf, property, eql, include, above, below, oneOf and not do the checking. A failed description throws a message that names the value it met and what it wanted. equal asks whether two things are the very same thing, so objects and arrays are compared with eql instead.
Take a guess: Why are long values in Chai's messages cut short, and can you change where they are cut?
pm.expect is how most tests check a value. It is Chai's expect, from the Chai library that Postman puts inside every script: you hand it a value, then describe what the value should be, in words joined by dots. pm.expect(95).to.be.above(90) reads almost as English: expect 95 to be above 90. If the description holds, nothing happens. If it does not, pm.expect throws an error whose message says what was expected and what came instead.
The words to, be, been, is, that, which, and, has, have and with change nothing; they are there so that the line reads well. The words that check are the rest. Here are the ones you will use most, on the list that GET /gauges answers:
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "list gauges",
request: "http://localhost:3000/gauges",
event: [{ listen: "test", script: { exec: [
"const list = pm.response.json();",
'pm.test("an array of 2", () => pm.expect(list).to.be.an("array").that.has.lengthOf(2));',
'pm.test("boiler first", () => pm.expect(list[0]).to.have.property("name", "boiler"));',
'pm.test("whole boiler", () => pm.expect(list[0]).to.eql({ name: "boiler", value: 95, unit: "C" }));',
'pm.test("has a pump", () => pm.expect(list.map((g) => g.name)).to.include("pump"));',
'pm.test("pump below 50", () => pm.expect(list[1].value).to.be.below(50));',
'pm.test("pump in bar or psi", () => pm.expect(list[1].unit).to.be.oneOf(["bar", "psi"]));',
'pm.test("boiler is no pump", () => pm.expect(list[0].name).to.not.equal("pump"));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✓ an array of 2
✓ boiler first
✓ whole boiler
✓ has a pump
✓ pump below 50
✓ pump in bar or psi
✓ boiler is no pump
| Check | Passes when | Example from the block |
|---|---|---|
a(type), an(type) | the value is of that type: string, number, array, object | to.be.an("array") |
lengthOf(n) | an array or a string has n items or letters | to.have.lengthOf(2) |
property(name, value) | an object has the field, with that value if one is given | to.have.property("name", "boiler") |
eql(value) | the value is deeply equal: the same fields with the same values | to.eql({ name: "boiler", ... }) |
include(item) | an array holds the item, or a string holds the text | to.include("pump") |
above(n), below(n) | a number is bigger, or smaller, than n | to.be.below(50) |
oneOf(list) | the value is one of the list's items | to.be.oneOf(["bar", "psi"]) |
not | turns the next check around | to.not.equal("pump") |
Describing what you expect
pm.expect is like telling a friend what to look for at the station: expect the train to be blue, to have eight coaches, and to be no later than ten. The friend checks each part, and if one is wrong, says which: expected eight coaches, but got six.
Reading the messages
A check is worth as much as its message, because the message is all you see on a busy morning. Here are six checks that fail on purpose, one of each kind:
Worked example 3
Read each failed check's message, and say from the message alone what was wrong.
What we have: six failing checks on the list of two gauges
What we need: for each message, what was expected and what came back
The plan: run them, then read each message as expected, then the value, then what it should have been
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "list gauges",
request: "http://localhost:3000/gauges",
event: [{ listen: "test", script: { exec: [
"const list = pm.response.json();",
'pm.test("three gauges", () => pm.expect(list).to.have.lengthOf(3));',
'pm.test("pump first", () => pm.expect(list[0]).to.have.property("name", "pump"));',
'pm.test("boiler at 96", () => pm.expect(list[0]).to.eql({ name: "boiler", value: 96, unit: "C" }));',
'pm.test("has a fan", () => pm.expect(list.map((g) => g.name)).to.include("fan"));',
'pm.test("boiler below 50", () => pm.expect(list[0].value).to.be.below(50));',
'pm.test("value is text", () => pm.expect(list[0].value).to.be.a("string"));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✗ three gauges | expected [ { name: 'boiler', …(2) }, …(1) ] to have a length of 3 but got 2
✗ pump first | expected { Object (name, value, ...) } to have property 'name' of 'pump', but got 'boiler'
✗ boiler at 96 | expected { Object (name, value, ...) } to deeply equal { Object (name, value, ...) }
✗ has a fan | expected [ 'boiler', 'pump' ] to include 'fan'
✗ boiler below 50 | expected 95 to be below 50
✗ value is text | expected 95 to be a string
- lengthOf says the length it got: 2 instead of 3. property says the value it found: boiler instead of pump. include and below show the value they were given.
- Long values are shortened to fit about 40 characters. Inside a list, Chai keeps what fits and writes …(2) for two fields it left out, or …(1) for one item, as in [ { name: 'boiler', …(2) }, …(1) ]. An object that still does not fit is written { Object (name, value, ...) }, with its first field names.
Each message names the check, the value it met and the value it wanted, so most failures can be understood without opening the answer at all.
Check: Six checks, six messages, each with the word expected first.
Another way: print the whole value with console.log in the test when a shortened message is not enough.
A path that fails: writing one test that checks everything at once. The first failed check throws and the rest never run, so the message tells only part of the story; one check per test tells all of it.
equal and eql
Two words look alike and behave very differently. equal asks whether two things are the same thing, as === does. For numbers and strings that is what you want. But two objects written separately are never the same object, even with the same fields. eql asks whether they are deeply equal: the same fields with the same values.
Worked example 4
Compare the boiler from the answer with an object written in the test, first with equal, then with eql.
What we have: the boiler's object from the list, and an object literal with the same three fields
What we need: which comparison passes
The plan: run both, and remember that equal compares identity while eql compares contents
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "list gauges",
request: "http://localhost:3000/gauges",
event: [{ listen: "test", script: { exec: [
"const list = pm.response.json();",
'pm.test("equal on objects", () => pm.expect(list[0]).to.equal({ name: "boiler", value: 95, unit: "C" }));',
'pm.test("eql on objects", () => pm.expect(list[0]).to.eql({ name: "boiler", value: 95, unit: "C" }));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✗ equal on objects | expected { Object (name, value, ...) } to equal { Object (name, value, ...) }
✓ eql on objects
- equal failed: the object in the answer and the object in the test are two different objects, even though they look the same.
- eql passed: it compared their fields one by one.
eql passes and equal fails: compare objects and arrays with eql.
Check: Both messages show the same shortened objects; only eql looks inside them.
A path that fails: checking an array with equal, such as to.equal(["boiler", "pump"]). It always fails, because a new array is never the same array; use eql.
When you are stuck: A check fails and I cannot see why
Read the message slowly: expected, then the value it met, then what it wanted.
Is the value shortened, with …(n) or { Object ... }? Print it with console.log(JSON.stringify(value)) to see all of it.
Comparing objects or arrays? Use eql, not equal.
Your turn
Which check passes for the value 95: to.be.above(90), or to.be.below(90)?Tap to reveal
- Above means bigger than.
to.be.above(90): 95 is bigger than 90.
Why does pm.expect([1, 2]).to.equal([1, 2]) fail?Tap to reveal
- equal asks whether two things are the same thing.
Because two arrays written separately are different objects; equal compares identity. Use eql.
cat > app.js <<'END'
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "list gauges",
request: "http://localhost:3000/gauges",
event: [{ listen: "test", script: { exec: [
"const list = pm.response.json();",
'pm.test("two names", () => pm.expect(list.map((g) => g.name)).to.eql(["boiler", "pump"]));',
'pm.test("a big boiler", () => pm.expect(list[0].value).to.be.above(99));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
✓ two names
✗ a big boiler | expected 95 to be above 99
- The names, in order, are boiler and pump, and eql compares contents.
- The boiler reads 95, which is not above 99.
It prints ✓ two names, then ✗ a big boiler | expected 95 to be above 99.
Did you know?
A cut at forty characters
The shortened values in Chai's messages follow a setting. Chai's documentation lists config.truncateThreshold, with a default of 40: when an actual or expected value in an assertion error is longer than that, it is truncated. Set it to zero, the documentation adds, if you want to disable truncating altogether.
Why it fits here: It answers this topic's question: Chai cuts long values at its truncateThreshold, 40 by default, and 0 turns the cutting off.
Source: Chai: Assertion Styles
A style that changes every object
Chai has more than one style. Besides expect, which Postman uses, there is should, which reads value.should.equal(3). Chai's documentation explains the catch: should extends each object with a should property to start the chain, and it warns that this style has some issues in Internet Explorer. expect leaves your objects alone.
Why it fits here: It explains why this topic's pm.expect is Chai's expect style: should adds a property to every object, expect adds nothing.
Source: Chai: Assertion Styles
In one line
pm.expect is Chai's expect: describe the value with words such as a, lengthOf, property, eql, include, above, oneOf and not. A failed description throws a message that says what it met and what it wanted; compare objects with eql, not equal.
Checking the response itself
At a glance
Some checks are about the answer as a whole: its status, its headers and the shape of its body.
pm.response.to has checks that know what a response is. to.have.status takes a code or a reason. to.be.ok means the reason OK. to.have.header checks a header, with or without its value. to.be.json, to.have.jsonBody and to.have.body look at the body. Their messages say response, so a failure is easy to place. The answer's parts are also there for pm.expect: code, status, json(), text(), headers.get() and the responseTime.
Take a guess: Does the order of the fields in a JSON answer ever matter?
pm.expect checks any value. For the response as a whole there is a shorter way: pm.response.to, followed by words that know what a response is. They come from a small library inside Postman, chai-postman, that adds response checks to Chai. pm.response.to.have.status(201) is shorter than pm.expect(pm.response.code).to.equal(201), and its message says response, so you know at once what failed.
| Check | Passes when |
|---|---|
to.have.status(201) | the status code is 201 |
to.have.status("Created") | the status reason is Created |
to.be.ok | the status reason is OK, which means the code is 200 |
to.have.header("Content-Type") | the response has that header |
to.have.header("Content-Type", "...") | the header has exactly that value |
to.be.json | the body is valid JSON |
to.have.jsonBody("name") | the JSON body has that field |
to.have.body("...") | the body is exactly that text |
The answer's parts are also there as plain values, for pm.expect: pm.response.code is the status code, pm.response.status its reason, pm.response.json() and pm.response.text() the body, pm.response.headers.get("Content-Type") one header, and pm.response.responseTime the milliseconds the answer took.
Here they are on a POST that adds a fan correctly:
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "add a gauge",
request: {
method: "POST",
url: "http://localhost:3000/gauges",
body: { mode: "raw", raw: '{ "name": "fan", "value": 12, "unit": "rpm" }', options: { raw: { language: "json" } } },
},
event: [{ listen: "test", script: { exec: [
'pm.test("created", () => pm.response.to.have.status(201));',
'pm.test("says Created", () => pm.response.to.have.status("Created"));',
'pm.test("answers JSON", () => pm.response.to.be.json);',
'pm.test("has a type", () => pm.response.to.have.header("Content-Type"));',
'pm.test("exact type", () => pm.response.to.have.header("Content-Type", "application/json; charset=utf-8"));',
'pm.test("echoes a name", () => pm.response.to.have.jsonBody("name"));',
'pm.test("quick", () => pm.expect(pm.response.responseTime).to.be.below(5000));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✓ created
✓ says Created
✓ answers JSON
✓ has a type
✓ exact type
✓ echoes a name
✓ quick
Every check passed. The last one, quick, compares the response time with a generous limit. The time itself changes on every run, so a test should never ask for an exact time, only an upper limit.
Checking a parcel at the door
When a parcel arrives, you check the label before you open it. Is it addressed to you? Is it the right kind of box? Does it carry the sender's stamp? In the same way, pm.response.to checks the label of an answer: its status, its headers and the shape of its body. Then pm.expect opens the box and checks what is inside.
The messages, when they fail
Here the POST sends a value that is a word, which the server refuses with 400 Bad Request. Five checks expect a success, and each fails with its own message:
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "add a bad gauge",
request: {
method: "POST",
url: "http://localhost:3000/gauges",
body: { mode: "raw", raw: '{ "name": "fan", "value": "twelve" }', options: { raw: { language: "json" } } },
},
event: [{ listen: "test", script: { exec: [
'pm.test("created", () => pm.response.to.have.status(201));',
'pm.test("ok", () => pm.response.to.be.ok);',
'pm.test("has the hall", () => pm.response.to.have.header("X-Hall"));',
'pm.test("plain text", () => pm.response.to.have.header("Content-Type", "text/plain"));',
'pm.test("echoes the value", () => pm.response.to.have.jsonBody("value"));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✗ created | expected response to have status code 201 but got 400
✗ ok | expected response to have status reason 'OK' but got 'BAD REQUEST'
✗ has the hall | expected response to have header with key 'X-Hall'
✗ plain text | expected 'Content-Type' response header to be 'text/plain' but got 'application/json; charset=utf-8'
✗ echoes the value | expected { error: 'value must be a number' } in response to contain property 'value'
Read them once. status gives the code it got, 400. to.be.ok gives the reason it got, BAD REQUEST, written in capitals. The header checks name the header, and the value they found. jsonBody shows the whole body it searched: here a short object, so it is shown in full.
Worked example 5
The server should refuse a reading whose value is not a number. Write tests that pass when it does.
What we have: a POST with the value "twelve", and a server that answers 400 with { error: "value must be a number" }
What we need: three tests that describe a correct refusal
The plan: check the status, the error message, and that nothing was echoed back as stored
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "add a bad gauge",
request: {
method: "POST",
url: "http://localhost:3000/gauges",
body: { mode: "raw", raw: '{ "name": "fan", "value": "twelve" }', options: { raw: { language: "json" } } },
},
event: [{ listen: "test", script: { exec: [
'pm.test("refused with 400", () => pm.response.to.have.status(400));',
'pm.test("says why", () => pm.expect(pm.response.json().error).to.equal("value must be a number"));',
'pm.test("stores nothing", () => pm.expect(pm.response.json()).to.not.have.property("name"));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✓ refused with 400
✓ says why
✓ stores nothing
- A test does not have to expect success. Here 400 is the right answer, so the test asks for 400.
- to.not.have.property("name") checks that the refusal did not pretend to store the gauge.
Three ticks: the server refused with 400, said why, and stored nothing.
Check: Send a good value, and these three tests would fail, which is what they should do.
A path that fails: testing only the happy path. An API that accepts a word as a reading would pass every success test; only a test for the refusal catches it.
When you are stuck: A response check fails unexpectedly
Print pm.response.code, pm.response.status and pm.response.text() in the test to see the answer itself.
Checking a header's value? Most servers add ; charset=utf-8 to a JSON Content-Type; check with to.have.header(name) and pm.expect(...).to.include("application/json") instead of the exact value.
to.be.ok fails for 201 Created: ok means the reason OK, which belongs to 200 alone.
Your turn
A POST answers 201 Created. Does pm.response.to.be.ok pass?Tap to reveal
- to.be.ok checks the status reason.
No: its reason is Created, and ok needs OK, which only 200 has.
Which check passes when the body has a field called error?Tap to reveal
- One of chai-postman's checks looks inside a JSON body.
pm.response.to.have.jsonBody("error").
cat > app.js <<'END'
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "add a gauge",
request: {
method: "POST",
url: "http://localhost:3000/gauges",
body: { mode: "raw", raw: '{ "name": "fan", "value": 12 }', options: { raw: { language: "json" } } },
},
event: [{ listen: "test", script: { exec: [
'pm.test("refused", () => pm.response.to.have.status(400));',
'pm.test("is JSON", () => pm.response.to.be.json);',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
✗ refused | expected response to have status code 400 but got 201
✓ is JSON
- A value of 12 is a number, so the server stores the fan and answers 201.
- The body is still JSON.
It prints ✗ refused | expected response to have status code 400 but got 201, then ✓ is JSON.
Did you know?
A JSON object has no order
The fields of a JSON object have no order. RFC 8259, the JSON standard of December 2017, defines an object as an unordered collection of name and value pairs, and notes that parsers differ on whether they show the order to programs at all. Software whose behaviour does not depend on the order works the same everywhere.
Why it fits here: It answers this topic's question: a JSON object is unordered, so a check should find fields by name, never by their position.
Source: RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format
A status for content that cannot be processed
The gauges server refuses a value that is not a number with 400 Bad Request. HTTP has a closer fit. RFC 9110 defines 422 Unprocessable Content for a request whose content type is understood and whose syntax is correct. The server was still unable to process it. A reading of twelve, written in words, is valid JSON that cannot be stored.
Why it fits here: It sharpens this topic's refusal tests: 422 says the request was well formed but its content could not be processed.
Source: RFC 9110: HTTP Semantics
In one line
pm.response.to checks the answer as a whole, its status, reason, headers and JSON body, with messages that say response; pm.response.code, json() and headers.get() give the parts for pm.expect; test a refusal as carefully as a success.
Failures, the summary and the exit code
At a glance
A failure helps only if someone finds out, so Newman reports it in three places.
The assertion event reports each failure as it happens. The summary's run.failures lists every one, with its test, its message, its request and its place in the script; a script that throws outside any test is recorded at test-script, and the rest of that script does not run. On the command line, the report repeats the failures, and the exit code is 1, unless -x keeps it at 0.
Take a guess: Where did the habit of writing small automated tests for code, like these, first spread from?
A test that fails is only useful if someone finds out. Newman reports every failure in three places: the assertion event as it happens, the summary at the end, and, on the command line, the report and the exit code. This section reads all three.
Every failure, in the summary
The summary's run.failures list holds one entry per failure. For a failed check, error.name is AssertionError, the kind of error Chai throws; error.test is the test's name and error.message its message; source.name is the request it ran after; and at says which test it was, by number. From these you can print a report of your own:
Worked example 6
Print a short report: how many tests passed, and for each failure, where it happened and why.
What we have: two requests with two tests each, and two tests that fail
What we need: a count, then one block of lines per failure
The plan: in newman.run's callback, read summary.run.stats.assertions for the count and summary.run.failures for the details
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const tests = (...lines) => [{ listen: "test", script: { exec: lines } }];
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "list gauges",
request: "http://localhost:3000/gauges",
event: tests('pm.test("answers 200", () => pm.response.to.have.status(200));', 'pm.test("three gauges", () => pm.expect(pm.response.json()).to.have.lengthOf(3));'),
},
{
name: "read the boiler",
request: "http://localhost:3000/gauges/boiler",
event: tests('pm.test("in Celsius", () => pm.expect(pm.response.json().unit).to.equal("C"));', 'pm.test("below 90", () => pm.expect(pm.response.json().value).to.be.below(90));'),
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, (err, summary) => {
const { total, failed } = summary.run.stats.assertions;
console.log(`${total - failed} of ${total} tests passed`);
summary.run.failures.forEach((f, i) => {
console.log(`${i + 1}. ${f.source.name} > ${f.error.test} (${f.error.name}, ${f.at})`);
console.log(` ${f.error.message}`);
});
server.close();
});
});
Terminal: node app.js
2 of 4 tests passed
1. list gauges > three gauges (AssertionError, assertion:1 in test-script)
expected [ { name: 'boiler', …(2) }, …(1) ] to have a length of 3 but got 2
2. read the boiler > below 90 (AssertionError, assertion:1 in test-script)
expected 95 to be below 90
- Four tests ran and two failed, so 2 of 4 passed.
- Each failure names its request and its test, the kind of error, and its number in the script: both failures were the second test of their script, assertion:1.
- The message under each one says what was wrong, in Chai's words.
2 of 4 tests passed; the failures are three gauges in list gauges and below 90 in read the boiler.
Check: The report's failures match the two checks that cannot hold: the list has 2 gauges, and the boiler reads 95.
Another way: Newman's own reporters print such a report for you on the command line, as the end of this section shows.
A script that breaks
A test that fails is one thing; a script that breaks is another. If a line outside any test throws, such as reading a field of something that does not exist, the rest of the script does not run, and Newman records a failure at test-script, without a test number:
Worked example 7
The test script reads pm.response.json().units.name, but the answer has unit, not units. What happens to the test after that line?
What we have: a script with a test, then a line that reads a field of undefined, then a second test
What we need: which tests ran, and what the summary records
The plan: run it, and watch for a failure that belongs to no test
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "read the boiler",
request: "http://localhost:3000/gauges/boiler",
event: [{ listen: "test", script: { exec: [
'pm.test("answers 200", () => pm.response.to.have.status(200));',
'const unit = pm.response.json().units.name;',
'pm.test("in Celsius", () => pm.expect(unit).to.equal("C"));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, (err, summary) => {
const s = summary.run.stats;
console.log("tests:", s.assertions.total, "| test scripts failed:", s.testScripts.failed);
for (const f of summary.run.failures) console.log(f.at, "|", f.error.name + ":", f.error.message);
server.close();
}).on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion));
});
Terminal: node app.js
✓ answers 200
tests: 1 | test scripts failed: 1
test-script | TypeError: Cannot read properties of undefined (reading 'name')
- The first test ran and passed.
- The next line threw a TypeError, so the script stopped there: the second test never ran, and only 1 test was counted.
- The summary records the failure at test-script, with the TypeError's own message, and counts one failed test script.
Only answers 200 ran. The script stopped at the broken line, and the failure is recorded at test-script as a TypeError.
Check: One test counted, one test script failed.
Another way: move the risky line inside a test: then only that test fails, and the tests after it still run.
A path that fails: looking only at the count of failed tests. A broken script can hide tests that never ran at all; the failures list shows it.
The exit code, and Newman's own reports
On the command line, all of this ends in the exit code. Here is a collection like the one above, with the list's test corrected to two gauges, so that one test still fails. It is shown below, and it runs twice. The first run uses Newman's usual report. The second adds -x, which keeps the exit code at 0, and asks for the json reporter instead, which writes the summary to a file; a line of Node then reads that file:
tests.postman_collection.json
{
"info": { "name": "Engine Hall gauges", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" },
"item": [
{ "name": "list gauges", "request": { "method": "GET", "url": "http://localhost:3000/gauges" },
"event": [ { "listen": "test", "script": { "exec": [
"pm.test(\"answers 200\", () => pm.response.to.have.status(200));",
"pm.test(\"two gauges\", () => pm.expect(pm.response.json()).to.have.lengthOf(2));"
] } } ] },
{ "name": "read the boiler", "request": { "method": "GET", "url": "http://localhost:3000/gauges/boiler" },
"event": [ { "listen": "test", "script": { "exec": [
"pm.test(\"in Celsius\", () => pm.expect(pm.response.json().unit).to.equal(\"C\"));",
"pm.test(\"below 90\", () => pm.expect(pm.response.json().value).to.be.below(90));"
] } } ] }
]
}
Terminal, measured on 2026-11-20 in the kit's sandbox: real Newman 6.2.3, Node 22.23.1 and Express 5.3.0
asha@tower:~/shop$ npx newman run tests.postman_collection.json --color off
newman
Engine Hall gauges
→ list gauges
GET http://localhost:3000/gauges [200 OK, 316B, 50ms]
✓ answers 200
✓ two gauges
→ read the boiler
GET http://localhost:3000/gauges/boiler [200 OK, 274B, 6ms]
✓ in Celsius
1. below 90
┌─────────────────────────┬──────────────────┬──────────────────┐
│ │ executed │ failed │
├─────────────────────────┼──────────────────┼──────────────────┤
│ iterations │ 1 │ 0 │
├─────────────────────────┼──────────────────┼──────────────────┤
│ requests │ 2 │ 0 │
├─────────────────────────┼──────────────────┼──────────────────┤
│ test-scripts │ 2 │ 0 │
├─────────────────────────┼──────────────────┼──────────────────┤
│ prerequest-scripts │ 0 │ 0 │
├─────────────────────────┼──────────────────┼──────────────────┤
│ assertions │ 4 │ 1 │
├─────────────────────────┴──────────────────┴──────────────────┤
│ total run duration: 141ms │
├───────────────────────────────────────────────────────────────┤
│ total data received: 120B (approx) │
├───────────────────────────────────────────────────────────────┤
│ average response time: 28ms [min: 6ms, max: 50ms, s.d.: 22ms] │
└───────────────────────────────────────────────────────────────┘
# failure detail
1. AssertionErr… below 90
expected 95 to be below 90
at assertion:1 in test-script
inside "read the boiler"
asha@tower:~/shop$ echo "exit: $?"
exit: 1
asha@tower:~/shop$ npx newman run tests.postman_collection.json -x --reporters json --reporter-json-export report.json
asha@tower:~/shop$ echo "exit: $?"
exit: 0
asha@tower:~/shop$ node -e "const r = require('./report.json'); console.log(r.run.stats.assertions); console.log(r.run.failures.map((f) => f.error.test + ': ' + f.error.message))"
{ total: 4, pending: 0, failed: 1 }
[ 'below 90: expected 95 to be below 90' ]
The first run's report shows each test under its request, a tick for a pass and a number for a failure, and the failure table repeats Chai's message: expected 95 to be below 90. The exit code is 1, so a build would stop. The second run printed nothing, because the json reporter writes only its file, and its exit code was 0, because of -x. The file holds the same summary the library gives you: the same counts, and the same failures.
When you are stuck: A build does not stop when a test fails
Is -x, --suppress-exit-code, in the command? It keeps the exit code at 0 whatever happens.
Does the build actually read newman run's exit code? A command after it in the same step can hide it.
Did the test really fail? A test whose function returns false passes.
Your turn
A failure's at says assertion:3 in test-script. Which test of its script was it?Tap to reveal
- Tests are numbered from 0.
The fourth test of the script.
A failure's at says test-script, with no number. What does that tell you?Tap to reveal
- Failed checks get a number; what else can fail?
The script itself threw outside any test, so the rest of the script did not run.
cat > app.js <<'END'
const newman = require("newman");
const app = require("./server");
const tests = (...lines) => [{ listen: "test", script: { exec: lines } }];
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "list gauges",
request: "http://localhost:3000/gauges",
event: tests('pm.test("answers 200", () => pm.response.to.have.status(200));', 'pm.test("three gauges", () => pm.expect(pm.response.json()).to.have.lengthOf(2));'),
},
{
name: "read the boiler",
request: "http://localhost:3000/gauges/boiler",
event: tests('pm.test("in Celsius", () => pm.expect(pm.response.json().unit).to.equal("C"));', 'pm.test("below 90", () => pm.expect(pm.response.json().value).to.be.below(90));'),
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, (err, summary) => {
const { total, failed } = summary.run.stats.assertions;
console.log(`${total - failed} of ${total} tests passed`);
summary.run.failures.forEach((f, i) => {
console.log(`${i + 1}. ${f.source.name} > ${f.error.test} (${f.error.name}, ${f.at})`);
console.log(` ${f.error.message}`);
});
server.close();
});
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
3 of 4 tests passed
1. read the boiler > below 90 (AssertionError, assertion:1 in test-script)
expected 95 to be below 90
- The list does have 2 gauges now, so that test passes.
- The boiler still reads 95, which is not below 90.
It prints 3 of 4 tests passed, then the one failure, below 90.
Did you know?
Born on a flight to Atlanta
Small automated tests spread through JUnit, a testing tool for Java. Martin Fowler, one of its early adopters, wrote that JUnit was born on a flight from Zurich to the 1997 OOPSLA conference in Atlanta, where Kent Beck was flying with Erich Gamma. With a long flight ahead, the two of them spent it programming.
Why it fits here: It answers this topic's question: the habit spread through JUnit, which Kent Beck and Erich Gamma began on a flight in 1997.
Sources: Martin Fowler: Xunit; Wikipedia: JUnit
Five reporters, one with emoji
Newman's own report is only one of several. Its README lists five built-in reporters: cli, json, junit, progress and emojitrain. The junit reporter writes the run's summary as a JUnit compatible XML file, the format that build servers read, named after the JUnit tool. And emojitrain does what its name suggests.
Why it fits here: It extends this topic's reports: Newman has five built-in reporters, from junit's XML for build servers to emojitrain.
Source: Newman on GitHub: README
In one line
Every failure lands in summary.run.failures with its test, message, request and place, a broken script at test-script; on the command line the report repeats them and the exit code is 1, unless -x keeps it at 0.
Where it is used
Tests are what turn a collection from a list of questions into a guard. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| pm.test and pm.expect | every collection that is run on its own | a check that every product has a price above zero |
| response checks | contracts between teams | the mobile team's tests that the API still answers JSON with the fields they read |
| tests for refusals | security and validation | a test that a request without a key is refused with 401 |
| the failures list | reports that people read | a morning report naming each failed check and its request |
| the exit code | build servers | a deployment that stops when one test fails |
| skipped tests | work in progress | a test written before the feature, skipped until it ships |
Teams often keep their API's collection, with its tests, beside the code, and run it with Newman or the Postman CLI on every change, so that a broken answer is caught before anyone outside sees it.
In the Testing House, a test is the red line under a card, pm.expect is the clerk's check, and the exit code is the red stamp on the report's cover.
Mistakes and debugging
These are the mistakes people make most with tests, each with the way to see it and the fix.
1. A test that returns false
A test fails only when its function throws. A function that returns false, or a comparison that is false, passes. Check with pm.expect or pm.response.to, which throw.
2. A check with no function
Leave out the arrow, and pm.test receives a true or false instead of a function. Measured with Newman, it then passes, whatever the value:
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "read the pump",
request: "http://localhost:3000/gauges/pump",
event: [{ listen: "test", script: { exec: [
'pm.test("is 404", pm.response.code === 404);',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✓ is 404
The pump answered 200, so the comparison was false, and still the test passed. Always give pm.test a function: () => followed by the check.
3. Many checks in one test
A test stops at its first failed check, so the checks after it are never tried:
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "read the pump",
request: "http://localhost:3000/gauges/pump",
event: [{ listen: "test", script: { exec: [
'pm.test("the pump is right", () => {',
' pm.expect(pm.response.json().name).to.equal("pump");',
' pm.expect(pm.response.json().value).to.equal(41);',
' pm.expect(pm.response.json().unit).to.equal("psi");',
'});',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, () => server.close())
.on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✗ the pump is right | expected 40 to equal 41
The value check failed, so the unit check never ran, and the report hides that the unit is wrong too. Give each check its own test, with its own name.
4. equal for objects and arrays
equal asks whether two things are the same thing; two objects written apart never are. Compare objects and arrays with eql.
5. Testing an exact time
A response's time changes on every run. Test it against a generous upper limit, such as below 5000 milliseconds, never for an exact value.
6. Only testing success
An API that accepts bad data passes every success test. Write tests for the refusals too: a bad value answered with 400, a missing gauge with 404.
The debugging corner: print before you check
When a test fails and the message is not enough, add console.log(pm.response.code, pm.response.text()) at the top of the script, and run again: you see exactly what the test saw. Remove it when the test is fixed.
In the app, the response pane's Test Results tab lists every test with its result, and the Console shows the script's messages.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
app.js (server.js is the gauges server from the tests section)
const newman = require("newman");
const app = require("./server");
const collection = {
info: { name: "Engine Hall gauges" },
item: [
{
name: "read the pump",
request: "http://localhost:3000/gauges/pump",
event: [{ listen: "test", script: { exec: [
'pm.test("answers 200", () => pm.response.to.have.status(200));',
'pm.test("answers JSON", () => pm.response.to.be.json);',
'pm.test("has a value", () => pm.response.to.have.jsonBody("value"));',
'pm.test("value is a number", () => pm.expect(pm.response.json().value).to.be.a("number"));',
'pm.test("in bar", () => pm.expect(pm.response.json()).to.have.property("unit", "bar"));',
'pm.test("above 50", () => pm.expect(pm.response.json().value).to.be.above(50));',
] } }],
},
],
};
const server = app.listen(3000, () => {
newman.run({ collection }, (err, summary) => {
const { total, failed } = summary.run.stats.assertions;
console.log(`${total - failed} of ${total} passed; exit code would be ${summary.run.failures.length ? 1 : 0}`);
server.close();
}).on("assertion", (err, args) => console.log((err ? "✗ " : "✓ ") + args.assertion + (err ? " | " + err.message : "")));
});
Terminal: node app.js
✓ answers 200
✓ answers JSON
✓ has a value
✓ value is a number
✓ in bar
✗ above 50 | expected 40 to be above 50
5 of 6 passed; exit code would be 1
| When you see | It means | Do |
|---|---|---|
| a test that never fails | it returns a value instead of throwing | check with pm.expect or pm.response.to |
| expected response to have status code 201 but got 400 | the server refused the request | read the body for the reason; test the refusal on purpose |
| expected { Object (...) } to equal { Object (...) } | equal used on objects | use eql |
| …(2) or { Object (name, ...) } in a message | Chai shortened a long value | print it with JSON.stringify |
| a failure at test-script, with no number | the script threw outside any test | fix the line, or move it inside a test |
| only the first problem reported | many checks in one test | one check per test |
| exit code 1 | at least one failure | read the failure table; -x only if you mean it |
The story: Every answer checked
Now every card ends with a few short lines in red: the answer must come back 200, as JSON, with a name and a number above zero. The runner checks each line and marks it with a tick or a cross.
The morning report is short. Its cover says how many checks passed and how many failed, and a failed check names the card, the line and what came back instead. A report with a single cross gets a red stamp, and the day's work waits until it is fixed.
The Postmaster hangs the last report on the wall. "The Testing House is in order," she says. "Next door they keep the yard's records in tables."
Reagents gathered: pm.test, pm.expect, assertion, failure, exit code, report.
Sources
- Newman's README (its command line options, library API, run events and reporters) (Apache-2.0 (the package's LICENSE.md, read 2026-11-20); facts and ideas only)
- Postman Learning Center (Postman's documentation of its app, collections, variables and scripts) (Not stated as open: Postman's own documentation (read 2026-11-20); facts and ideas only)
- The Express documentation (CC BY-SA 3.0 US (the site's footer, read 2026-11-15); facts and ideas only)