Loading

T10 Postman · Lesson 2

Collections

A collection grows: requests go into folders, an address is written once as a variable, and one test can guard every request. Sort a collection into folders and know the order they run in, use collection variables, write scripts for a whole collection or folder, and run it all again and again with the Collection Runner and Newman.

  • sort the requests of a collection into folders and subfolders, and say in what order Newman runs them
  • run one folder, or a few, with Newman's folder option, and read the error for a name it cannot find
  • write collection variables once and use them in URLs, headers and bodies with double braces
  • read and change collection variables from a script, and spot a misspelt variable by what it sends
  • write pre-request and test scripts for a whole collection or folder, and say in what order they run
  • run a collection several times, stop it at the first failure, and say what the app's Collection Runner adds
About 70 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-20); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-20); Express, from npm (the kit compares every Express block with it, in its sandbox; the page runs the small Express of plan 25) 5.3.0 (2026-11-20); Newman, Postman's collection runner from npm, with postman-runtime 7.39.1 and Chai 4.4.1 in its script sandbox (the kit compares every Newman block with it, in its sandbox; the page runs the small Newman of plan 33) 6.2.3 (2026-11-20)Play this lesson's games

The back cover

A box of questions that only grows soon becomes a heap. The same address is written on every card, the same check is copied onto every card, and finding the five cards you need means reading all forty.

These pages give a growing collection its shape. They sort requests into folders and show the order in which a run walks them. They keep shared values in collection variables, put shared checks in scripts that guard every request, and run the whole box, or one drawer of it, as many rounds as needed.

Before you start

The story: A box with no drawers

By the next morning the box of questions holds twenty cards. Readings are mixed with changes, and every card carries the yard's whole address, written out by hand. When the yard moves its door to another port, a clerk spends an hour correcting every card, and misses two.

Worse, some checks belong on every card: did the answer come back in the yard's own script? Each clerk copies that check onto each card, a little differently each time.

Postmaster Meera Franking taps the lid. "Drawers inside," she says, "one for readings, one for changes. The address written once, on the lid. A note inside the lid that every card obeys. And a runner who can carry one drawer or the whole box, as many rounds as I ask."

In lesson 01 a collection was a short list: three requests, one after another. Real collections grow. An API with twenty routes soon has forty requests, and a list of forty is hard to read, hard to change and slow to run when you only care about five of them.

This lesson gives a growing collection its shape. Folders group requests. Collection variables hold a value, such as the server's address, in one place for every request. Collection scripts run around every request inside them. And the Collection Runner in the app, like Newman, runs it all, one folder or the whole box, as many rounds as you ask.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
A collection and its items.item: [{ name: "list gauges", request: ... }]Folders are items that hold items.
The order of a run.top to bottom, one at a timeThe order of requests inside folders.
newman.run and its events..on("beforeItem", ...)Seeing which requests ran.
The summary.summary.run.statsCounting scripts, rounds and failures.
A first test.pm.test("status is 200", ...)One test for every request.
JSON bodies and their type.language: "json"Variables inside a body.
URLs, hosts and ports.http://localhost:3000An address kept in one variable.
JavaScript variables.let count = 0The idea behind collection variables.
The gauges server.require("./server")Every block's server, as in lesson 01.
The exit code.exit: 1Stopping at the first failure.

By the end of this lesson you will be able to:

  • sort the requests of a collection into folders and subfolders, and say in what order Newman runs them;
  • run one folder, or a few, with Newman's folder option, and read the error for a name it cannot find;
  • write collection variables once and use them in URLs, headers and bodies with double braces;
  • read and change collection variables from a script, and spot a misspelt variable by what it sends;
  • write pre-request and test scripts for a whole collection or folder, and say in what order they run;
  • run a collection several times, stop it at the first failure, and say what the app's Collection Runner adds.

How to follow this lesson

As in lesson 01, every block is one program: it starts the gauges server from server.js, runs a collection with Newman's library, prints what happened and closes the server. It runs on the page with the small Newman, and it has also been run with the real Newman 6.2.3, where it prints the same.

The app's parts are described in words from Postman's own documentation: the Variables tab, a collection's Scripts tab and the Collection Runner. Each one is matched with the JSON it writes, or with the Newman option that does the same job.

In one line

A growing collection needs shape: folders to group its requests, collection variables to keep shared values in one place, collection scripts to run around every request, and a runner to run it all.

Folders and their order

At a glance

A collection with forty requests needs drawers. Folders are those drawers.

A folder is an item that holds its own list of items, so folders can hold requests and other folders. Newman sends the requests in the order of the tree, going down into each folder as it meets it and finishing it before going on. Its folder option runs only the folders or requests it names, still in the collection's order, and a name that matches nothing stops the run before it starts.

Take a guess: Did a misspelt folder name always stop Newman with an error message?

A folder is a box inside the box. In the collection's JSON it is an item that has its own item list instead of a request. A folder can hold requests and other folders, called subfolders, as deep as you like. Folders only group; a folder sends nothing itself.

Here is the gauges collection sorted into folders. The readings folder holds two GET requests. The changes folder holds the POST that adds the fan, and a subfolder, checks, with the request that reads the fan back. One request, read the pump, stays at the top level, outside every folder. The collection is kept in its own module, collection.js, so that the blocks of this section can share it. In which order does Newman send its five requests? Here is the collection, and a run that prints each request's name and status:

collection.js

module.exports = {
  info: { name: "Engine Hall gauges" },
  item: [
    {
      name: "readings",
      item: [
        { name: "list gauges", request: "http://localhost:3000/gauges" },
        { name: "read the boiler", request: "http://localhost:3000/gauges/boiler" },
      ],
    },
    {
      name: "changes",
      item: [
        {
          name: "add the fan",
          request: {
            method: "POST",
            url: "http://localhost:3000/gauges",
            body: { mode: "raw", raw: '{ "name": "fan", "value": 12 }', options: { raw: { language: "json" } } },
          },
        },
        { name: "checks", item: [{ name: "read the fan", request: "http://localhost:3000/gauges/fan" }] },
      ],
    },
    { name: "read the pump", request: "http://localhost:3000/gauges/pump" },
  ],
};

app.js (server.js is the gauges server; collection.js is shown above)

const newman = require("newman");
const app = require("./server");
const collection = require("./collection");
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("request", (err, args) => console.log(args.item.name, "|", args.response.code))
    .on("done", () => server.close());
});

Terminal: node app.js

list gauges | 200
read the boiler | 200
add the fan | 201
read the fan | 200
read the pump | 200

Newman walks the tree from the top. It enters the first folder, readings, and sends its requests in order. Then it enters changes: the POST first, then the subfolder checks and the request inside it. Only then does it come out to read the pump. The rule is short: go down into each folder as you meet it, finish it, then go on. It is the order you would read the tree aloud, top to bottom.

The app's runner puts folders first

Postman's documentation says that the app's Collection Runner runs the requests in folders first, and then the requests at the root of the collection. Newman follows the item list exactly as the collection's file writes it, so a root request written between two folders runs between them.

To get the same order in both, keep the root requests after the folders, as in the collection above.

A book's contents page

A collection with folders reads like the contents page of a book: Part 1, its chapters, Part 2, its chapters and sections. You read every line of Part 1 before Part 2 begins. Newman reads the tree the same way, and sends each request when it reaches its line.

In the app

In Postman, a folder is made from the collection's View more actions menu, with Add folder; the same menu on a folder makes a subfolder. Requests are dragged into folders, and requests and folders can be dragged into a new order inside the collection, or sorted by name. A new order in the collection is a new order for every run of it.

Worked example 1

Here is a collection called A day in the hall. Before you run it, say the order in which its four requests will be sent.

What we have: a folder morning, holding a subfolder boiler (read the boiler) and then list gauges; then read the pump at the top level; then a folder evening (read the fan)

What we need: the order of the four requests

The plan: read the tree from the top, going into each folder as you meet it, then print the name of each item as it begins

  1. morning comes first, and inside it the subfolder boiler comes first, so read the boiler is sent first.
  2. Still inside morning, list gauges comes next.
  3. Out of morning, the top-level read the pump is next, and evening's read the fan comes last.

app.js (server.js is the gauges server)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "A day in the hall" },
  item: [
    {
      name: "morning",
      item: [
        { name: "boiler", item: [{ name: "read the boiler", request: "http://localhost:3000/gauges/boiler" }] },
        { name: "list gauges", request: "http://localhost:3000/gauges" },
      ],
    },
    { name: "read the pump", request: "http://localhost:3000/gauges/pump" },
    { name: "evening", item: [{ name: "read the fan", request: "http://localhost:3000/gauges/fan" }] },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("beforeItem", (err, args) => console.log(args.item.name))
    .on("done", () => server.close());
});

Terminal: node app.js

read the boiler
list gauges
read the pump
read the fan
  1. The beforeItem event fired for the four requests only. Folders send nothing, so they get no item events of their own.

read the boiler, list gauges, read the pump, read the fan.

Check: Four requests, four names, in the order of the tree read top to bottom.

Another way: the app's Collection Runner, which runs the requests in folders first, would send read the pump last; Newman keeps the order the file writes.

A path that fails: guessing that top-level requests come first, before any folder. Newman does not sort by depth: read the pump waited for the whole of morning.

Running one folder

Often you want only part of a collection: the readings, or only the changes. Newman's folder option names what to run. It takes the name of a folder, or of a single request, anywhere in the tree:

app.js (server.js is the gauges server, and collection.js the collection shown above)

const newman = require("newman");
const app = require("./server");
const collection = require("./collection");
const server = app.listen(3000, () => {
  newman.run({ collection, folder: "changes" })
    .on("request", (err, args) => console.log(args.item.name, "|", args.response.code))
    .on("done", () => server.close());
});

Terminal: node app.js

add the fan | 201
read the fan | 200

Only the changes folder ran, with its subfolder inside it. The option also takes a list of names. The list's order does not matter: the requests still run in the order of the collection.

app.js (server.js is the gauges server, and collection.js the collection shown above)

const newman = require("newman");
const app = require("./server");
const collection = require("./collection");
const server = app.listen(3000, () => {
  newman.run({ collection, folder: ["read the pump", "readings"] })
    .on("request", (err, args) => console.log(args.item.name, "|", args.response.code))
    .on("done", () => server.close());
});

Terminal: node app.js

list gauges | 200
read the boiler | 200
read the pump | 200

The list put read the pump first, but the run sent the readings first, because that is their order in the tree. On the command line the same option is --folder, given once for each name: newman run gauges.postman_collection.json --folder readings --folder "read the pump". In the app, the Collection Runner can run a folder too: select the folder in the sidebar, then Run.

Worked example 2

Run only the checks subfolder, which reads the fan back. What does the fan's request answer, and why?

What we have: the collection above; checks holds one request, read the fan

What we need: the status of read the fan when checks runs alone

The plan: give the folder option the subfolder's name, and print each request's status

app.js (server.js is the gauges server, and collection.js the collection shown above)

const newman = require("newman");
const app = require("./server");
const collection = require("./collection");
const server = app.listen(3000, () => {
  newman.run({ collection, folder: "checks" })
    .on("request", (err, args) => console.log(args.item.name, "|", args.response.code))
    .on("done", () => server.close());
});

Terminal: node app.js

read the fan | 404
  1. Only read the fan was sent, and the server answered 404.
  2. In a full run, add the fan comes before checks and stores the fan. Run alone, checks never sees that POST, and every block starts a fresh server, so there is no fan to read.

404: run alone, the subfolder misses the POST that its request relies on.

Check: Run the changes folder instead, and the fan's request answers 200, as the earlier block showed.

Another way: run ["add the fan", "checks"]: the list keeps the collection's order, so the POST still comes first.

A path that fails: assuming a folder carries the work of the requests outside it. A folder run sends only the requests inside it; anything they rely on must run in the same run.

A name that matches no folder and no request stops the run before it starts: no event fires, and the callback receives an error and no summary. Here the name has a letter missing:

app.js (server.js is the gauges server, and collection.js the collection shown above)

const newman = require("newman");
const app = require("./server");
const collection = require("./collection");
const server = app.listen(3000, () => {
  newman.run({ collection, folder: "reading" }, (err, summary) => {
    console.log(err ? err.message : "the run went ahead");
    console.log("summary:", summary);
    server.close();
  });
});

Terminal: node app.js

runtime~extractRunnableItems: Unable to find a folder or request: "reading"
summary: undefined

When you are stuck: A request did not run

Is it inside the folder you named, or inside one of its subfolders? Only those run.

Is the name exactly right, letter for letter? A name with a letter missing stops the whole run with Unable to find a folder or request.

Did it rely on a request outside the folder? Add that request's name to the list, or run the folder above both.

Your turn

A collection holds folder A (request a1, then folder A2 with request a2), then request b. In which order are a1, a2 and b sent?Tap to reveal
  1. Go down into each folder as you meet it.
  2. Finish a folder before going on.

a1, a2, b.

You run with folder: ["b", "A"]. Which request is sent first?Tap to reveal
  1. Does the list's order decide the run's order?

a1: a list of names keeps the collection's order, so folder A's requests come before b.

cat > app.js <<'END'
const newman = require("newman");
const app = require("./server");
const collection = require("./collection");
const server = app.listen(3000, () => {
  newman.run({ collection, folder: "readings" })
    .on("request", (err, args) => console.log(args.item.name, "|", args.response.code))
    .on("done", () => 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
list gauges | 200
read the boiler | 200
  1. The folder option names readings.
  2. Its two requests run in order, and both gauges exist.

It prints list gauges | 200, then read the boiler | 200.

Did you know?

A misspelt folder once said nothing

Newman has not always reported a folder name it could not find. Its changelog for version 6.0.0, dated 15 September 2023, lists a fixed bug: an invalid folder input used to exit silently. Before that release, a run given a misspelt folder name could end there and then, with no message to say why.

Why it fits here: It answers this topic's question: the clear error for an unknown folder name arrived only with Newman 6.0.0, in 2023.

Source: Newman's changelog

Folders inside folders, then several at once

Newman learned folders in steps. Version 3.5.0, of 7 March 2017, added folders inside folders to its command-line, HTML and JUnit reports. Version 4.1.0, of 29 August 2018, added the ability to choose several folders for one run, which is why the folder option can take a list, and --folder can be given more than once.

Why it fits here: It dates this topic's folder option: several folders in one run have been possible since Newman 4.1.0, in 2018.

Source: Newman's changelog

In one line

A folder is an item with its own item list. Newman sends the requests in the order of the tree, finishing each folder before going on, and its folder option runs only what it names, in the collection's order.

Collection variables

At a glance

When forty requests share one address, the address should be written once.

A collection variable is a named value kept in the collection's variable list. Anywhere in a request, the name in double curly braces is replaced by the value just before sending: in the URL, in a header and in the body. Scripts read and change collection variables with pm.collectionVariables, and a value set by one request lasts for the rest of the run. A name that matches no variable stays as written.

Take a guess: Can Postman make up test data, such as a random first name, all by itself?

Look back at lesson 01's collections: every request wrote out http://localhost:3000. If the server moved to another port, every request would need changing, and missing one would break it quietly. Values that many requests share should be written once.

A collection variable is a named value kept in the collection itself, in its variable list of key and value pairs. Anywhere in a request, {{base}}, the name in double curly braces, is replaced by the variable's value just before the request is sent. Here two requests share the address, and one also uses a gauge's name:

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [
    { key: "base", value: "http://localhost:3000" },
    { key: "gauge", value: "boiler" },
  ],
  item: [
    { name: "list gauges", request: "{{base}}/gauges" },
    { name: "read one gauge", request: "{{base}}/gauges/{{gauge}}" },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("request", (err, args) => console.log(args.request.url.toString(), "|", args.response.code))
    .on("done", () => server.close());
});

Terminal: node app.js

http://localhost:3000/gauges | 200
http://localhost:3000/gauges/boiler | 200

The printed addresses show the values already in place: Newman replaced {{base}} and {{gauge}} before sending. The server never sees the braces. Change the base in one place, and every request moves with it.

The address on the lid

Think of the collection as a box of letters, all for one yard. Instead of writing the yard's full address on every letter, you write it once on the lid, and each letter says only "the address on the lid". When the yard moves, you change the lid.

In headers and bodies too

The braces work anywhere a request has text: the URL, a header's value, and the body. In a JSON body a variable can even stand for a number, without quotes around it, because the replacement happens in the text before the body is sent:

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [
    { key: "base", value: "http://localhost:3000" },
    { key: "gauge", value: "fan" },
    { key: "reading", value: 12 },
  ],
  item: [
    {
      name: "add a gauge",
      request: {
        method: "POST",
        url: "{{base}}/gauges",
        body: { mode: "raw", raw: '{ "name": "{{gauge}}", "value": {{reading}} }', options: { raw: { language: "json" } } },
      },
    },
    { name: "read it back", request: "{{base}}/gauges/{{gauge}}" },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("request", (err, args) => console.log(args.item.name, "|", args.response.code, args.response.text()))
    .on("done", () => server.close());
});

Terminal: node app.js

add a gauge | 201 {"name":"fan","value":12}
read it back | 200 {"name":"fan","value":12}

The body { "name": "{{gauge}}", "value": {{reading}} } went out as { "name": "fan", "value": 12 }, which is valid JSON, so the server stored the fan. The second request used the same gauge variable to read it back.

In the app

In Postman, open Collections in the sidebar, select the collection and choose its Variables tab. Each row is one variable, with its name and its value. Postman's documentation describes collection variables as available throughout the requests of a collection, and suited to details such as the URL. Lesson 03 adds environments, which hold values that change from one server to another.

Reading and changing them from a script

Scripts reach collection variables through pm.collectionVariables: get("name") reads one, set("name", value) writes one, unset("name") removes one and has("name") asks whether it exists. A value set by one request's script is there for every request after it, for the rest of the run:

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [{ key: "base", value: "http://localhost:3000" }],
  item: [
    {
      name: "read the boiler",
      request: "{{base}}/gauges/boiler",
      event: [{ listen: "test", script: { exec: ['pm.collectionVariables.set("boiler", pm.response.json().value);'] } }],
    },
    {
      name: "report",
      request: "{{base}}/gauges",
      event: [{ listen: "prerequest", script: { exec: [
        'const boiler = pm.collectionVariables.get("boiler");',
        'console.log("the boiler read", boiler, "and is a", typeof boiler);',
      ] } }],
    },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("console", (err, args) => console.log(args.messages.join(" ")))
    .on("done", () => server.close());
});

Terminal: node app.js

the boiler read 95 and is a number

The first request's test saved the boiler's reading. The second request's pre-request script read it back. The value kept its type, a number, because a variable holds whatever the script gave it; only when it is put into the text of a URL, a header or a body does it become text.

Changes last only for the run

A value set during a run lives until the run ends. Newman never writes it back into your collection file: measured with Newman, even its --export-collection option, which saves the collection at the end of a run, saves the values the run started with. In the app, the Collection Runner keeps such changes only when its Keep variable values setting is on.

Worked example 3

The gauges server has moved to port 3001. Change the collection so that both of its requests reach it, with one edit.

What we have: two requests that start with {{base}}, and a base of http://localhost:3000

What we need: both requests answered by the server on port 3001

The plan: change the base variable's value, and nothing else in the requests

  1. Both requests begin with {{base}}, so the address lives in one place: the variable list.
  2. Set base to http://localhost:3001. In this block the server also listens on 3001, to stand for the move.

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [{ key: "base", value: "http://localhost:3001" }],
  item: [
    { name: "list gauges", request: "{{base}}/gauges" },
    { name: "read the pump", request: "{{base}}/gauges/pump" },
  ],
};
const server = app.listen(3001, () => {
  newman.run({ collection })
    .on("request", (err, args) => console.log(args.request.url.toString(), "|", args.response.code))
    .on("done", () => server.close());
});

Terminal: node app.js

http://localhost:3001/gauges | 200
http://localhost:3001/gauges/pump | 200
  1. Both printed addresses carry the new port, and both requests were answered.

Change one value: base becomes http://localhost:3001, and both requests follow.

Check: Both lines show :3001 and a 200.

A path that fails: editing each request's URL by hand. With two requests it works; with forty, one is always missed.

Worked example 4

A request should read the boiler, but the server answers 404. Find out why from what Newman sent.

What we have: the url {{base}}/gauges/{{guage}} and the variables base and gauge

What we need: the cause of the 404, and the fix

The plan: print the address as sent, and compare each name in braces with the variable list

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [
    { key: "base", value: "http://localhost:3000" },
    { key: "gauge", value: "boiler" },
  ],
  item: [{ name: "read one gauge", request: "{{base}}/gauges/{{guage}}" }],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("request", (err, args) => console.log(args.request.url.toString(), "|", args.response.code))
    .on("done", () => server.close());
});

Terminal: node app.js

http://localhost:3000/gauges/%7B%7Bguage%7D%7D | 404
  1. The address ends in %7B%7Bguage%7D%7D. %7B and %7D are { and } written as codes, so the braces were never replaced.
  2. A name in braces that matches no variable is left as it was written. The url says guage, with the u and the a swapped, but the variable is gauge.
  3. The server looked for a gauge literally called {{guage}}, found none, and answered 404.

The url misspells the variable: {{guage}} for {{gauge}}. Fix the spelling, and the request reads the boiler.

Check: After the fix, the address printed would end in /gauges/boiler.

A path that fails: checking the server first. The server did its job; the clue was in the address Newman sent.

When you are stuck: A variable was not replaced

Print the address as sent, args.request.url.toString(): braces or %7B%7B in it mean a name matched no variable.

Compare the name letter by letter with the variable list; names are matched exactly.

Was the variable set by a script in a request that runs later, or not at all in this run? A value exists only after the script that sets it has run.

Your turn

A collection has the variable base, with the value http://localhost:3000. What address does the request {{base}}/gauges/fan go to?Tap to reveal
  1. The braces and the name are replaced by the value.

http://localhost:3000/gauges/fan.

One request's test runs pm.collectionVariables.set("count", 3). The next request's pre-request script runs pm.collectionVariables.get("count"). What does it get, and of what type?Tap to reveal
  1. A value set by one request lasts for the rest of the run.
  2. A variable keeps the type it was given.

3, a number.

cat > app.js <<'END'
const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [
    { key: "base", value: "http://localhost:3000" },
    { key: "gauge", value: "pump" },
  ],
  item: [{ name: "read one gauge", request: "{{base}}/gauges/{{gauge}}" }],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("request", (err, args) => console.log(args.response.text()))
    .on("done", () => 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
{"name":"pump","value":40}
  1. {{gauge}} is replaced by pump.
  2. The pump exists, so the server answers with its reading.

It prints {"name":"pump","value":40}.

Did you know?

Variables that make up data

Postman can invent test data on its own. Variables whose names start with a dollar sign, such as {{$guid}} and {{$timestamp}}, get a fresh value each time a request runs, generated by the Faker library. The list is long and playful: {{$randomFirstName}}, {{$randomCity}}, the URL of a random cat image, and {{$randomBs}}, a random phrase of business-speak.

Why it fits here: It answers this topic's question: Postman's dynamic variables, whose names start with a dollar sign, make up fresh data for every request.

Source: Postman Docs: Use dynamic variables to return randomly generated data

A newer API than it looks

The pm.collectionVariables that scripts use in this lesson is younger than it looks. postman-sandbox, the engine that runs Postman's scripts, added support for it in version 3.4.0, dated 1 October 2019. The same changelog shows the engine growing feature by feature, each one listed with the date it arrived.

Why it fits here: It dates this topic's script API: pm.collectionVariables reached Postman's script engine in October 2019.

Source: postman-sandbox's changelog

In one line

A collection variable is a named value kept in the collection; {{name}} in a URL, header or body is replaced by it before sending, scripts read and change it with pm.collectionVariables, and a name that matches nothing stays as written.

Scripts for a whole collection

At a glance

Some checks belong to every request, and copying them forty times invites mistakes.

A collection and each folder can carry their own pre-request and test scripts, in their own event lists. They run around every request inside them: before the request, the collection's script first, then each folder's from the outside in, then the request's own; after the answer, the same order again. Inside them, pm.info.requestName names the request they are running for. Each run of a script counts once in the summary.

Take a guess: Can a Postman script use a library such as lodash without installing anything?

Some checks belong to every request. Did the answer come back as JSON? Did the server stay up, with no 500 error? Copying the same test into forty requests is slow, and the forty copies drift apart as people edit them. A better home for such a check is the collection itself.

A collection, and every folder, can have its own scripts, in its own event list, written exactly like a request's: a pre-request script, which listens for "prerequest", and a test script, which listens for "test". A collection's scripts run around every request in the collection. A folder's scripts run around every request inside that folder, its subfolders included.

Who runs first

When one request has scripts at three levels, in which order do they run? This block gives a collection, a folder and a request one message each, before and after:

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const say = (listen, words) => ({ listen, script: { exec: [`console.log("${words}");`] } });
const collection = {
  info: { name: "Engine Hall gauges" },
  event: [say("prerequest", "collection, before"), say("test", "collection, after")],
  item: [
    {
      name: "readings",
      event: [say("prerequest", "readings folder, before"), say("test", "readings folder, after")],
      item: [
        {
          name: "list gauges",
          request: "http://localhost:3000/gauges",
          event: [say("prerequest", "the request, before"), say("test", "the request, after")],
        },
      ],
    },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("console", (err, args) => console.log(args.messages.join(" ")))
    .on("request", (err, args) => console.log("  (list gauges answered " + args.response.code + ")"))
    .on("done", () => server.close());
});

Terminal: node app.js

collection, before
readings folder, before
the request, before
  (list gauges answered 200)
collection, after
readings folder, after
the request, after

Before the request, the order is outside in: the collection's pre-request script, then the folder's, then the request's own. After the answer, the test scripts run in the same order again: collection, folder, request. With deeper folders, each folder takes its turn from the outermost to the innermost.

LevelIts pre-request script runsIts test script runs
the collectionfirst, before every request in the collectionfirst, after every answer
a foldernext, before every request inside itnext, after every answer inside it
the requestlast, just before it is sentlast, after its own answer

Rules of the house, the floor and the room

Think of a building. The house rules apply in every room, then the floor's rules for the rooms on that floor, then the room's own notice on its door. You read them in that order every time you enter a room, and again as you leave.

One test for every request

Here is the JSON check written once, as a collection test. It runs after every answer. Two of the requests reach routes of the gauges server, which always answers JSON, even for a missing gauge. The third has a typing slip in its path, /gauge, which no route of the server matches:

Worked example 5

Find which request did not answer in JSON, with one test written once for the whole collection.

What we have: three requests, and a test at the collection level that checks the Content-Type of every answer

What we need: the requests whose answer is not JSON

The plan: read the assertion events, which name each request, and the failures in the summary

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  event: [
    {
      listen: "test",
      script: { exec: ['pm.test("answers JSON", () => pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"));'] },
    },
  ],
  item: [
    { name: "list gauges", request: "http://localhost:3000/gauges" },
    { name: "read the chimney", request: "http://localhost:3000/gauges/chimney" },
    { name: "a wrong path", request: "http://localhost:3000/gauge" },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection }, (err, summary) => {
    for (const failure of summary.run.failures) console.log("failed:", failure.source.name, "|", failure.error.message);
    server.close();
  }).on("assertion", (err, args) => console.log(args.item.name, "|", args.assertion, err ? "failed" : "passed"));
});

Terminal: node app.js

list gauges | answers JSON passed
read the chimney | answers JSON passed
a wrong path | answers JSON failed
failed: a wrong path | expected 'text/html; charset=utf-8' to include 'application/json'
  1. One test, three results: the collection test ran once after each answer, and args.item.name tells which answer.
  2. The chimney's answer was a 404, but in JSON, so it passed: this test checks the type, not the status.
  3. The wrong path reached no route at all. Express's own fallback answered it with an HTML page, text/html, so the test failed.

a wrong path: its answer was text/html, Express's page for a route that does not exist.

Check: Fix the path to /gauges and run again: all three pass.

A path that fails: adding the JSON test to each request by hand. It works today, and the forty copies drift apart the first time one of them is changed.

Inside a collection or folder script, pm.info.requestName names the request it is running for, so one script can still tell the requests apart.

In the app, and in the summary

In Postman, a collection and a folder each have a Scripts tab of their own, with the same two parts as a request's: Pre-request and Post-response. Postman's documentation says that a collection's pre-request script runs before every request in the collection, and a folder's before every request inside it.

The summary counts each script that ran as one script. One request with scripts at the collection, the folder and itself counts three test scripts, not one:

Worked example 6

A collection test, a folder test and one request's own test: how many test scripts run for the two requests of the folder, and how many tests?

What we have: a collection test answered (status below 500), a folder test found (status 200), and a test boiler is 95 on read the boiler only

What we need: the number of test scripts and of tests in the summary

The plan: count the scripts around each request, then run and read summary.run.stats

  1. list gauges runs the collection's test script and the folder's: 2.
  2. read the boiler runs those two and its own: 3.
  3. So 5 test scripts in all, and since each script holds one test, 5 tests.

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const check = (name, code) => ({ listen: "test", script: { exec: [`pm.test("${name}", () => ${code});`] } });
const collection = {
  info: { name: "Engine Hall gauges" },
  event: [check("answered", "pm.expect(pm.response.code).to.be.below(500)")],
  item: [
    {
      name: "readings",
      event: [check("found", "pm.response.to.have.status(200)")],
      item: [
        { name: "list gauges", request: "http://localhost:3000/gauges" },
        {
          name: "read the boiler",
          request: "http://localhost:3000/gauges/boiler",
          event: [check("boiler is 95", "pm.expect(pm.response.json().value).to.equal(95)")],
        },
      ],
    },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection }, (err, summary) => {
    const s = summary.run.stats;
    console.log("test scripts:", s.testScripts.total, "| tests:", s.assertions.total, "| failed:", s.assertions.failed);
    server.close();
  });
});

Terminal: node app.js

test scripts: 5 | tests: 5 | failed: 0

5 test scripts and 5 tests, none failed.

Check: 2 for the first request plus 3 for the second is 5, as the summary says.

A path that fails: counting 3 test scripts, one per place they are written. The summary counts runs, and the collection's and the folder's scripts run once for each request.

When you are stuck: A collection test fails where it should not

Does the test make sense for every request it runs after? A status is 200 test fails for a POST that answers 201; move it to a folder of reads.

Print pm.info.requestName inside the script to see which request it is running for.

Is it running twice? A check written in the collection and again in a request runs twice for that request.

Your turn

A request sits inside folder F, inside collection C. All three have test scripts. In which order do the test scripts run after the answer?Tap to reveal
  1. The order is the same as before the request.

C, then F, then the request's own.

Why can a status is 200 test written on the collection fail for a request that worked?Tap to reveal
  1. A collection test runs after every request.
  2. Which status does a POST that stores something send?

Because it runs after every request, including a POST that answers 201; such a test belongs on a folder of reads.

cat > app.js <<'END'
const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  event: [{ listen: "prerequest", script: { exec: ['console.log("about to ask:", pm.info.requestName);'] } }],
  item: [
    { name: "read the boiler", request: "http://localhost:3000/gauges/boiler" },
    { name: "read the pump", request: "http://localhost:3000/gauges/pump" },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("console", (err, args) => console.log(args.messages.join(" ")))
    .on("done", () => 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
about to ask: read the boiler
about to ask: read the pump
  1. The collection's pre-request script runs before each request.
  2. pm.info.requestName names the request each time.

It prints about to ask: read the boiler, then about to ask: read the pump.

Did you know?

A toolbox built into every script

Postman's scripts come with libraries already inside. Its documentation says the require method gives a script the sandbox's built-in library modules, among them lodash, moment, cheerio, chai and xml2js, with nothing to install. A few older ones, such as crypto-js, atob, btoa and tv4, are now listed as deprecated and no longer supported, each with a modern replacement.

Why it fits here: It answers this topic's question: require gives a Postman script built-in libraries such as lodash, with nothing to install.

Source: Postman Docs: Import packages into your scripts

The old way of writing tests

Before pm, Postman's scripts used bare names such as tests, responseCode and responseBody. postman-sandbox 4.7.0, dated 1 April 2024, deprecated these legacy APIs and added a warning in the console when a script uses one. Its code pairs each old name with its replacement: tests with pm.test(), and responseCode with pm.response.code.

Why it fits here: It explains the scripts of old tutorials: the bare names they use are legacy APIs, deprecated in 2024 in favour of pm.

Sources: postman-sandbox's changelog; postman-sandbox: the legacy interface

In one line

A collection and each folder can carry pre-request and test scripts that run around every request inside them, in the order collection, folder, request; each run of a script counts as one in the summary.

Running the whole collection

At a glance

A collection is built to be run again and again, and the runner decides how.

iterationCount runs every request several times, and pm.info.iteration counts the rounds from 0, while a collection variable lives through all of them. By default Newman goes on after a failure and reports every one; bail stops the run when the failing item ends. The app's Collection Runner offers the same choices, with iterations, a delay and a setting that stops at an error, which is on by default.

Take a guess: Can a collection run change its own order, or loop over one request?

A collection is built to be run, again and again: after every change to the server, every morning, before every release. Postman's app has a tool for that, the Collection Runner, and Newman offers the same choices as options. This section looks at the most useful ones: how many rounds, which part, and what to do when something fails.

Rounds: iterations

One pass through every request of a run is an iteration. Newman's iterationCount option asks for several. Inside a script, pm.info.iteration says which round it is, counting from 0, and pm.info.iterationCount says how many there are. A collection variable lives through all the rounds of one run, so it can count them:

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [{ key: "rounds", value: 0 }],
  item: [
    {
      name: "list gauges",
      request: "http://localhost:3000/gauges",
      event: [{ listen: "test", script: { exec: [
        'pm.collectionVariables.set("rounds", pm.collectionVariables.get("rounds") + 1);',
        'console.log("round", pm.info.iteration, "of", pm.info.iterationCount, "| rounds so far:", pm.collectionVariables.get("rounds"));',
      ] } }],
    },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection, iterationCount: 3 }, (err, summary) => {
    console.log("iterations:", summary.run.stats.iterations.total, "| requests:", summary.run.stats.requests.total);
    server.close();
  }).on("console", (err, args) => console.log(args.messages.join(" ")));
});

Terminal: node app.js

round 0 of 3 | rounds so far: 1
round 1 of 3 | rounds so far: 2
round 2 of 3 | rounds so far: 3
iterations: 3 | requests: 3

Three rounds, numbered 0, 1 and 2, as arrays are. The variable began at 0 and each round added one, so it went on from where the last round left it. Why run the same requests several times? To see that an API gives the same answer every time; to catch a fault that shows only now and then; and, in lesson 03, to feed each round different data.

Worked example 7

Run the collection three times, and check that the number of requests sent matches.

What we have: one request, and the option iterationCount: 3

What we need: the rounds that ran, and the requests sent

The plan: count from the summary: iterations, and requests, which should be the rounds times the requests in one round

  1. Each round sends every request of the run once: here, one request per round.
  2. Three rounds of one request make 3 requests, and the summary says iterations 3 and requests 3, as the block above printed.
  3. With the five-request collection of the folders section, three rounds would send 15.

3 iterations and 3 requests: rounds times requests per round.

Check: The console lines show rounds 0, 1 and 2, one request each.

A path that fails: expecting pm.info.iteration to start at 1. It counts from 0, so the last of three rounds is round 2.

When something fails: go on, or stop

By default, Newman goes on after a failure. A failed test, a script that throws an error, a request that gets no answer: each is recorded, and the next request is sent anyway. Here the chimney's test fails in the middle of the run:

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const found = [{ listen: "test", script: { exec: ['pm.test("found", () => pm.response.to.have.status(200));'] } }];
const collection = {
  info: { name: "Engine Hall gauges" },
  item: [
    { name: "read the boiler", request: "http://localhost:3000/gauges/boiler", event: found },
    { name: "read the chimney", request: "http://localhost:3000/gauges/chimney", event: found },
    { name: "read the pump", request: "http://localhost:3000/gauges/pump", event: found },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection, bail: false }, (err, summary) => {
    console.log("requests sent:", summary.run.stats.requests.total);
    server.close();
  }).on("assertion", (err, args) => console.log(args.item.name, "|", args.assertion, err ? "failed" : "passed"));
});

Terminal: node app.js

read the boiler | found passed
read the chimney | found failed
read the pump | found passed
requests sent: 3

All three requests were sent, and the pump's test still ran. That is usually what you want: one run tells you about every failure at once, not only the first.

Sometimes it is not. If logging in fails, the forty requests after it are pointless, and their failures only hide the real one. The bail option stops the run at the first failure: Newman finishes the item where the failure happened, then ends the run.

Worked example 8

Stop the run at the first failure, and say which requests were sent.

What we have: the same three requests, and the option bail: true

What we need: the requests that ran before the run stopped

The plan: set bail to true, and read the assertion events and the summary

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const found = [{ listen: "test", script: { exec: ['pm.test("found", () => pm.response.to.have.status(200));'] } }];
const collection = {
  info: { name: "Engine Hall gauges" },
  item: [
    { name: "read the boiler", request: "http://localhost:3000/gauges/boiler", event: found },
    { name: "read the chimney", request: "http://localhost:3000/gauges/chimney", event: found },
    { name: "read the pump", request: "http://localhost:3000/gauges/pump", event: found },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection, bail: true }, (err, summary) => {
    console.log("requests sent:", summary.run.stats.requests.total);
    server.close();
  }).on("assertion", (err, args) => console.log(args.item.name, "|", args.assertion, err ? "failed" : "passed"));
});

Terminal: node app.js

read the boiler | found passed
read the chimney | found failed
requests sent: 2
  1. The boiler passed, and the chimney failed. Newman finished the chimney's item, its test script included, and then stopped.
  2. The pump's request was never sent: the summary counts 2 requests, not 3.

read the boiler and read the chimney; the run stopped after the chimney's failure, so the pump was never asked.

Check: Run it again without bail, as the block before did, and 3 requests are sent.

Another way: on the command line the same switch is --bail: newman run gauges.postman_collection.json --bail.

A path that fails: using bail on a morning check of forty independent requests. The first failure would hide all the others, and you would fix them one run at a time.

The Collection Runner in the app

In Postman, select a collection or a folder in the sidebar and choose Run. The Collection Runner opens. For the kind of run this lesson describes, its run type is Functional, run Locally. Before you start, it offers choices:

In the Collection RunnerWhat it doesIn Newman
Iterationsthe number of roundsiterationCount, or -n
Iteration dataa data file, one row for each round (lesson 03)iterationData, or -d
a collection or a folderwhat to runfolder, or --folder
Add a delay ofmilliseconds to wait before each requestdelayRequest, or --delay-request
Stop run if an error occursstop at a script's error or a request that cannot be sent; on by defaultbail, or --bail; off by default
Keep variable valueskeep the variables a run changed, after it endsnothing: a run never changes the collection file
ticking and dragging requestsleave some out, or change their order for this runthe folder option, or a new order in the collection

Notice the different defaults. The app's runner stops at an error in a script or a request it cannot send, unless you clear that setting. Newman goes on unless you ask it to bail. After a run, the runner shows each request with its test results, round by round, and a Console log tab with every script's messages.

The same run on the command line

Here is the readings folder run twice on the command line, with a collection test that checks for JSON. The collection file is the folders section's one, with {{base}} for the address and the JSON test written once on the collection:

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 gauges.postman_collection.json --folder readings -n 2 --color off
newman

Engine Hall gauges

Iteration 1/2

❏ readings
↳ list gauges
  GET http://localhost:3000/gauges  [200 OK, 258B, 50ms]
  ✓  answers JSON

↳ read the boiler
  GET http://localhost:3000/gauges/boiler  [200 OK, 263B, 6ms]
  ✓  answers JSON

Iteration 2/2

↳ list gauges
  GET http://localhost:3000/gauges  [200 OK, 258B, 4ms]
  ✓  answers JSON

↳ read the boiler
  GET http://localhost:3000/gauges/boiler  [200 OK, 263B, 3ms]
  ✓  answers JSON

┌─────────────────────────┬──────────────────┬──────────────────┐
│                         │         executed │           failed │
├─────────────────────────┼──────────────────┼──────────────────┤
│              iterations │                2 │                0 │
├─────────────────────────┼──────────────────┼──────────────────┤
│                requests │                4 │                0 │
├─────────────────────────┼──────────────────┼──────────────────┤
│            test-scripts │                4 │                0 │
├─────────────────────────┼──────────────────┼──────────────────┤
│      prerequest-scripts │                0 │                0 │
├─────────────────────────┼──────────────────┼──────────────────┤
│              assertions │                4 │                0 │
├─────────────────────────┴──────────────────┴──────────────────┤
│ total run duration: 156ms                                     │
├───────────────────────────────────────────────────────────────┤
│ total data received: 102B (approx)                            │
├───────────────────────────────────────────────────────────────┤
│ average response time: 15ms [min: 3ms, max: 50ms, s.d.: 19ms] │
└───────────────────────────────────────────────────────────────┘
asha@tower:~/shop$ echo "exit: $?"
exit: 0

Read the new parts. Each round opens with Iteration 1/2, then 2/2: the command line counts rounds from 1, while pm.info.iteration counts from 0. The line ❏ readings names the folder when the run enters it, and each request inside a folder is marked ↳, where lesson 01's top-level requests were marked →. In the second round the folder's name is not printed again, because the run never left it. The table counts 2 iterations, 4 requests and 4 test runs of the one collection test, all passed, so the exit code is 0.

When you are stuck: The rounds do not do what I expect

Does a value carry over from one round to the next? Collection variables do, for the whole run; a fresh value needs resetting at the start of each round.

Is pm.info.iteration off by one? It counts from 0; the command line's Iteration 1/2 counts from 1.

Did the run stop early? Look for bail in the options, or Stop run if an error occurs in the app.

Your turn

A run has 4 requests and iterationCount: 5. How many requests are sent, if nothing stops it?Tap to reveal
  1. Every round sends every request once.

20: 5 rounds of 4 requests.

Requests A, B and C each have a test; B's test fails. Which requests are sent with bail: true, and which without?Tap to reveal
  1. Without bail, Newman goes on.
  2. With bail, it finishes the failing item and stops.

With bail: A and B. Without: A, B and C.

cat > app.js <<'END'
const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [{ key: "rounds", value: 0 }],
  item: [
    {
      name: "list gauges",
      request: "http://localhost:3000/gauges",
      event: [{ listen: "test", script: { exec: [
        'pm.collectionVariables.set("rounds", pm.collectionVariables.get("rounds") + 1);',
        'console.log("round", pm.info.iteration, "of", pm.info.iterationCount, "| rounds so far:", pm.collectionVariables.get("rounds"));',
      ] } }],
    },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection, iterationCount: 2 }, (err, summary) => {
    console.log("iterations:", summary.run.stats.iterations.total, "| requests:", summary.run.stats.requests.total);
    server.close();
  }).on("console", (err, args) => console.log(args.messages.join(" ")));
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
round 0 of 2 | rounds so far: 1
round 1 of 2 | rounds so far: 2
iterations: 2 | requests: 2
  1. Two rounds, numbered from 0.
  2. The variable keeps counting across the rounds.

It prints round 0 and round 1 with 1 and 2 rounds so far, then iterations: 2 | requests: 2.

Did you know?

A run that steers itself

A collection run does not have to follow the list. Postman's documentation shows a test calling pm.execution.setNextRequest() to name the request that runs next. Given the current request's own name, it runs that request again after it completes, a loop; given null, the collection run stops after the current request runs.

Why it fits here: It answers this topic's question: setNextRequest lets a run pick its next request, loop over one, or stop.

Source: Postman Docs: Customize request order in a collection run

Many users at once

The Collection Runner can also test speed. In a performance test, Postman runs a collection with a chosen number of virtual users. Each virtual user runs the requests in order, in a repeating loop, and all of them work in parallel to stand for real users at once. The load can stay fixed, ramp up, or spike and fall back.

Why it fits here: It shows another use of this topic's runner: the same collection, run by many virtual users at once, tests an API's speed under load.

Source: Postman Docs: Configure and run performance tests

In one line

iterationCount runs every request of a run several times, with pm.info.iteration counting rounds from 0; Newman goes on after a failure unless bail stops it, while the app's Collection Runner stops at an error by default.

Where it is used

Every collection that lives longer than a week grows folders, variables and shared checks. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
folders and their orderany API with more than a handful of routesa folder for each part of a shop's API: products, carts, orders
the folder optionrunning only what a change touchedrunning the orders folder after a change to the orders code
collection variablesvalues shared by many requeststhe server's address, or the version in /v2/ paths
collection and folder scriptschecks that belong to every requestevery answer is JSON, and arrives within a second
iterationschecking that answers stay the samerunning a collection ten times to catch a fault that shows now and then
bailruns where one failure makes the rest pointlessstopping a build's run as soon as logging in fails

Build your own collections in this shape from the start: a variable for the address, a folder for each part of the API, and scripts at the top for what every request shares.

In the Testing House, the drawers are the folders, the address on the lid is the collection variable, and the note inside the lid is the collection script.

Mistakes and debugging

These are the mistakes people make most as their collections grow, each with the way to see it and the fix.

1. A misspelt variable at the start of the address

When the misspelt name is the address itself, the braces stay where the host should be, and Newman tries to find a machine called {{bse}}:

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [{ key: "base", value: "http://localhost:3000" }],
  item: [{ name: "list gauges", request: "{{bse}}/gauges" }],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("request", (err, args) => console.log(args.request.url.toString(), "|", err ? err.message : args.response.code))
    .on("done", () => server.close());
});

Terminal: node app.js

http://{{bse}}/gauges | getaddrinfo ENOTFOUND {{bse}}

getaddrinfo is the call that turns a host name into a machine's address, and ENOTFOUND means no such name exists. A name in braces inside the error is the clue: fix the variable's name. In the path, the same slip shows as %7B%7B...%7D%7D and a 404, as the variables section showed.

2. A collection test that does not fit every request

A test written on the collection runs after every request, including the ones it was never meant for:

app.js (server.js is the gauges server from the request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  event: [{ listen: "test", script: { exec: ['pm.test("status is 200", () => pm.response.to.have.status(200));'] } }],
  item: [
    { name: "list gauges", request: "http://localhost:3000/gauges" },
    {
      name: "add the fan",
      request: {
        method: "POST",
        url: "http://localhost:3000/gauges",
        body: { mode: "raw", raw: '{ "name": "fan", "value": 12 }', options: { raw: { language: "json" } } },
      },
    },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection })
    .on("assertion", (err, args) => console.log(args.item.name, "|", err ? err.message : "passed"))
    .on("done", () => server.close());
});

Terminal: node app.js

list gauges | passed
add the fan | expected response to have status code 200 but got 201

The POST did exactly what it should, and answered 201 Created, but the collection's status is 200 test still ran after it. Move such a test to a folder of reads, or write it so that it fits every request, such as a status below 500.

3. Running a subfolder that relies on what is outside it

A folder run sends only the requests inside the folder. A read whose gauge is added by a POST in another folder finds nothing: name both in the folder option, or run the folder that holds both.

4. A folder name with a letter wrong

The folder option matches names exactly. One wrong letter ends the run before it starts, with Unable to find a folder or request and the name, and no summary at all. Copy the name from the collection instead of typing it.

5. Counting rounds from 1

pm.info.iteration counts from 0, so the first round is 0 and the last of three is 2. The command line's report, Iteration 1/2, counts from 1. Add 1 when you print a round for people.

6. Expecting the run to stop, or to save

Newman goes on after a failure unless bail is set, and a value set by a script lasts only until the run ends. To stop at the first failure, use bail; to keep a value for the next run, write it in the collection's variable list.

The debugging corner: print where you are

When a collection misbehaves, print three things from the events: the request's name from beforeItem, its address as sent from request, and pm.info.requestName from inside any collection or folder script. Together they tell you which request ran, where it went, and which script ran for it.

In the app, the Collection Runner's results list every request of every round with its tests, and its Console log tab shows every script's messages, grouped by request.

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 request section)

const newman = require("newman");
const app = require("./server");
const collection = {
  info: { name: "Engine Hall gauges" },
  variable: [{ key: "base", value: "http://localhost:3000" }],
  event: [{ listen: "test", script: { exec: ['pm.test("answered", () => pm.expect(pm.response.code).to.be.below(500));'] } }],
  item: [
    {
      name: "readings",
      item: [
        { name: "list gauges", request: "{{base}}/gauges" },
        { name: "read the boiler", request: "{{base}}/gauges/boiler" },
      ],
    },
    {
      name: "changes",
      item: [
        {
          name: "add the fan",
          request: {
            method: "POST",
            url: "{{base}}/gauges",
            body: { mode: "raw", raw: '{ "name": "fan", "value": 12 }', options: { raw: { language: "json" } } },
          },
        },
      ],
    },
  ],
};
const server = app.listen(3000, () => {
  newman.run({ collection, folder: "readings", iterationCount: 2 }, (err, summary) => {
    const s = summary.run.stats;
    console.log("rounds:", s.iterations.total, "| requests:", s.requests.total, "| tests failed:", s.assertions.failed);
    server.close();
  }).on("request", (err, args) => console.log(args.item.name, "|", args.response.code));
});

Terminal: node app.js

list gauges | 200
read the boiler | 200
list gauges | 200
read the boiler | 200
rounds: 2 | requests: 4 | tests failed: 0
When you seeIt meansDo
Unable to find a folder or requestthe folder option names nothing in the treecopy the name from the collection
%7B%7Bname%7D%7D in the addressa name in braces matched no variablefix the name, or add the variable
getaddrinfo ENOTFOUND {{name}}a misspelt variable where the host should befix the variable's name
404 for a request in a folder run aloneit relied on a request outside the folderrun both in the same run
a collection test failing for a POSTa test that does not fit every requestmove it to a folder, or make it fit all
round 0 in pm.info.iterationrounds are counted from 0add 1 when printing for people
the run went on after a failureNewman's defaultbail: true, or --bail
a script's value gone in the next runa run never changes the collection filewrite it in the collection's variable list

The story: Drawers and a lid

The box now has two drawers, Readings and Changes, and a small drawer inside Changes for the checks that follow them. The yard's address is written once, on the lid, and every card points to it. A note inside the lid checks every answer that comes back.

The runner carries the Readings drawer alone, twice round, and comes back with two neat reports. Told to stop at the first broken card, the runner stops there and says which card it was.

The Postmaster nods. "Tomorrow the same box must work for two yards," she says, "the practice yard and the real one, without rewriting a single card."

Reagents gathered: folder, collection variable, collection script, iteration, Collection Runner, bail.

Sources