Saving tests in a collection
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)After every change you click through forty requests and read each response by eye. On the fortieth you miss a product price of 0 that should be 349, and it ships.
Post-response scripts: pm.test and pm.expect
A post-response script is JavaScript in a request's Scripts tab that Postman runs right after the response arrives. Its tests report pass or fail for that response.
Open a request's Scripts tab, then Post-response, and write one named test. The examples test the login response.
Example 1 · Two tests on the login request
pm.test("Status is 200", function () { pm.response.to.have.status(200);});const body = pm.response.json();pm.test("Token is returned", function () { pm.expect(body.accessToken).to.be.a("string").and.not.empty; pm.expect(body.tokenType).to.eql("Bearer");});pm.environment.set("token", body.accessToken);$ newman run shoplite-api.postman_collection.json -e local.postman_environment.json --env-var "adminPassword=$SHOPLITE_ADMIN_PASSWORD" --folder Auth --reporter-cli-no-summary --reporter-cli-no-banner ShopLite API □ Auth └ Log in as admin POST http://localhost:8080/api/v1/auth/login [200 OK, 231B, 102ms] √ Status is 200 √ Token is returned
What this code does
pm.testgives each check a name, andpm.expectstates the rule. Both rules held, so both tests show a tick.- The last line is not a test: it saves the token for the next requests, as the variables section explains. The
√mark is how Windows terminals show the tick.
Older Postman versions call this tab Tests. Inside it, pm.test("name", function () { ... }) defines one named test, and pm.expect(value) states what the value must be, such as pm.expect(body.tokenType).to.eql("Bearer"). If any expect inside a test fails, that test fails. Tests read every response, every time, and never miss a price of 0 on the fortieth request.
You need only a little JavaScript; the Snippets list beside the script editor writes common tests for you ("Status code: Code is 200"). Results appear in the Test Results tab with a pass or fail mark per test name, so give each test a clear name that says what it checks.
pm.expect inside always passes. Every test needs at least one real check.Checking status, headers, response time and JSON fields
pm.test defines one named check, and pm.expect states what a value must be. If an expect inside a test fails, that test fails and its message shows both values.
Four kinds of checks cover most API tests: status, headers, response time and body fields. The examples run all four.
Example 2 · Status, header, time and body checks across the collection
pm.test("Status is 200", function () { pm.response.to.have.status(200);});pm.test("Content-Type is JSON", function () { pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");});pm.test("Answers in under 500 ms", function () { pm.expect(pm.response.responseTime).to.be.below(500);});pm.test("Only category 4, cheapest first", function () { const products = pm.response.json().content; pm.expect(products).to.have.lengthOf(3); products.forEach(p => pm.expect(p.categoryId).to.eql(4)); const prices = products.map(p => p.price); pm.expect(prices).to.eql([...prices].sort((a, b) => a - b));});$ newman run shoplite-api.postman_collection.json -e local.postman_environment.json --env-var "adminPassword=$SHOPLITE_ADMIN_PASSWORD" --reporter-cli-no-summary --reporter-cli-no-banner ShopLite API □ Auth └ Log in as admin POST http://localhost:8080/api/v1/auth/login [200 OK, 231B, 62ms] √ Status is 200 √ Token is returned □ Products └ List accessories by price GET http://localhost:8080/api/v1/products?categoryId=4&sort=price,asc [200 OK, 563B, 22ms] √ Status is 200 √ Content-Type is JSON √ Answers in under 500 ms √ Only category 4, cheapest first └ Create product POST http://localhost:8080/api/v1/products [201 Created, 296B, 7ms] √ Status is 201 √ Location points to the new product √ Saved with the price we sent └ Get product GET http://localhost:8080/api/v1/products/16 [200 OK, 260B, 8ms] √ Status is 200 √ It is the product we created └ Delete product DELETE http://localhost:8080/api/v1/products/16 [204 No Content, 111B, 5ms] √ Status is 204 and the body is empty └ Get deleted product GET http://localhost:8080/api/v1/products/16 [404 Not Found, 291B, 3ms] √ Status is 404 after the delete √ Error uses Problem Details
What this code does
- The code is the script of List accessories by price; every other request has its own short script. Fourteen checks in total, all passing.
- The last test checks the data itself: three products, all in category 4, and the prices already in ascending order.
[...prices].sort(...)makes a sorted copy to compare with.
Example 3 · A failing test and its message
// The same test, written when the API "should" return 4 accessoriespm.test("Only category 4, cheapest first", function () { const products = pm.response.json().content; pm.expect(products).to.have.lengthOf(4); products.forEach(p => pm.expect(p.categoryId).to.eql(4));});$ newman run shoplite-api.postman_collection.json -e local.postman_environment.json --env-var "adminPassword=$SHOPLITE_ADMIN_PASSWORD" --reporter-cli-no-summary --reporter-cli-no-banner
ShopLite API
□ Auth
└ Log in as admin
POST http://localhost:8080/api/v1/auth/login [200 OK, 231B, 98ms]
√ Status is 200
√ Token is returned
□ Products
└ List accessories by price
GET http://localhost:8080/api/v1/products?categoryId=4&sort=price,asc [200 OK, 563B, 10ms]
√ Status is 200
√ Content-Type is JSON
√ Answers in under 500 ms
1. Only category 4, cheapest first
└ Create product
POST http://localhost:8080/api/v1/products [201 Created, 296B, 6ms]
√ Status is 201
√ Location points to the new product
√ Saved with the price we sent
└ Get product
GET http://localhost:8080/api/v1/products/16 [200 OK, 260B, 10ms]
√ Status is 200
√ It is the product we created
└ Delete product
DELETE http://localhost:8080/api/v1/products/16 [204 No Content, 111B, 8ms]
√ Status is 204 and the body is empty
└ Get deleted product
GET http://localhost:8080/api/v1/products/16 [404 Not Found, 291B, 5ms]
√ Status is 404 after the delete
√ Error uses Problem Details
# failure detail
1. AssertionError Only category 4, cheapest first
expected [ …(3) ] to have a length of 4 but got 3
at assertion:3 in test-script
inside "Products / List accessories by price"What this code does
- The failing test gets a number instead of a tick, and the failure table at the end says what was expected and what came back: a length of 4, but 3 arrived.
- Decide which side is wrong. If an accessory was really deleted, the API is fine and the test needs updating; if it should exist, you found a bug.
Status: pm.response.to.have.status(201). Headers: pm.response.headers.get("Content-Type") returns the header text, so check it with to.include("application/json"). Time: pm.response.responseTime is in milliseconds, so to.be.below(500) catches a slow endpoint. Body: pm.response.json() turns the JSON body into an object whose fields you check one by one. The assertions come from a library called Chai: to.eql(4), to.include("text"), to.be.above(0), to.have.lengthOf(3), to.be.a("string"), to.have.property("id").
A failing check prints both values, for example expected [ …(3) ] to have a length of 4 but got 3. Watch the JSON types: the API sends "price": 349.00, a number, and JavaScript reads it as 349. So to.eql(349) passes, while to.eql("349.00") fails, because a number is never equal to a string.
Fix the error
Fix the failing test
Read the failure message, then pick the line that fixes it.
Round 1 of 2
The API sends "price": 349.00. The test fails.
Error
AssertionError: expected 349 to deeply equal '349.00'
Saving values into variables from scripts
pm.collectionVariables.set("name", value) stores a value from a script in a collection variable. pm.environment.set does the same for the selected environment.
A script can write variables as well as read responses. The login request saves the token, and every later request sends it.
Example 4 · The token chain, and what happens when login fails
Collection "ShopLite API" -> Authorization: Bearer Token {{token}}Auth / Log in as admin -> Authorization: No Auth Body: {"email": "{{adminEmail}}", "password": "{{adminPassword}}"} Post-response: pm.environment.set("token", body.accessToken);This run: adminPassword has no value$ newman run shoplite-api.postman_collection.json -e local.postman_environment.json --reporter-cli-no-summary --reporter-cli-no-banner
ShopLite API
□ Auth
└ Log in as admin
POST http://localhost:8080/api/v1/auth/login [401 Unauthorized, 299B, 91ms]
1. Status is 200
2. Token is returned
□ Products
└ List accessories by price
GET http://localhost:8080/api/v1/products?categoryId=4&sort=price,asc [200 OK, 563B, 8ms]
√ Status is 200
√ Content-Type is JSON
√ Answers in under 500 ms
√ Only category 4, cheapest first
└ Create product
POST http://localhost:8080/api/v1/products [401 Unauthorized, 341B, 7ms]
3. Status is 201
4. Location points to the new product
5. Saved with the price we sent
└ Get product
GET http://localhost:8080/api/v1/products/null [400 Bad Request, 309B, 5ms]
6. Status is 200
7. It is the product we created
└ Delete product
DELETE http://localhost:8080/api/v1/products/null [400 Bad Request, 309B, 7ms]
8. Status is 204 and the body is empty
└ Get deleted product
GET http://localhost:8080/api/v1/products/null [400 Bad Request, 309B, 17ms]
9. Status is 404 after the delete
10. Error uses Problem Details
# failure detail
01. AssertionError Status is 200
expected response to have status code 200 but got 401
at assertion:0 in test-script
inside "Auth / Log in as admin"
02. AssertionError Token is returned
expected undefined to be a string
at assertion:1 in test-script
inside "Auth / Log in as admin"
03. AssertionError Status is 201
expected response to have status code 201 but got 401
at assertion:0 in test-script
inside "Products / Create product"
04. AssertionError Location points to the new product
expected undefined to deeply equal 'http://localhost:8080/api/v1/products/undefined'
at assertion:1 in test-script
inside "Products / Create product"
05. AssertionError Saved with the price we sent
expected undefined to deeply equal 'BK-WINGS'
at assertion:2 in test-script
inside "Products / Create product"
06. AssertionError Status is 200
expected response to have status code 200 but got 400
at assertion:0 in test-script
inside "Products / Get product"
07. AssertionError It is the product we created
expected undefined to deeply equal NaN
at assertion:1 in test-script
inside "Products / Get product"
08. AssertionError Status is 204 and the body is empty
expected response to have status code 204 but got 400
at assertion:0 in test-script
inside "Products / Delete product"
09. AssertionError Status is 404 after the delete
expected response to have status code 404 but got 400
at assertion:0 in test-script
inside "Products / Get deleted product"
10. AssertionError Error uses Problem Details
expected 'The request has 1 invalid field.' to include 'not found'
at assertion:1 in test-script
inside "Products / Get deleted product"What this code does
- Log in got
401, so no token was saved. List accessories still passed because reading products needs no login; Create product failed with401, and every request after it used/products/null. - Ten failures, one cause. Read the failure table from the top: failure 01 says the login returned 401. With the password set, Example 2 shows the same collection fully green.
pm.environment.set("token", body.accessToken) stores the login token in the selected environment, and pm.collectionVariables.unset(...) removes a value that is no longer valid. Read any variable from a script with pm.variables.get("name"), which follows the same scope order as {{name}}. The common pattern is a login request first: its script saves the token, and the collection's Authorization tab is set to Bearer Token with the value {{token}}. Every request that inherits auth then sends a fresh token.
A token is a secret, so save it in a secret environment variable with an empty initial value: it then stays only on your computer. And make the login test strict: when the login fails, every later request fails too, and the first failure is the one to read.
Running a whole collection in order with the Collection Runner
The Collection Runner sends every request of a collection, or of one folder, in order and runs all their tests. It then lists which requests and tests passed and which failed.
Open the collection's ... menu → Run, pick the environment and click the Run button. The example shows a whole run with its summary.
Example 5 · A whole run with its summary
Runner settings Collection: ShopLite API (Auth, then Products) Environment: ShopLite Local Iterations: 1 Delay: 0 ms$ newman run shoplite-api.postman_collection.json -e local.postman_environment.json --env-var "adminPassword=$SHOPLITE_ADMIN_PASSWORD" newman ShopLite API □ Auth └ Log in as admin POST http://localhost:8080/api/v1/auth/login [200 OK, 231B, 141ms] √ Status is 200 √ Token is returned □ Products └ List accessories by price GET http://localhost:8080/api/v1/products?categoryId=4&sort=price,asc [200 OK, 563B, 19ms] √ Status is 200 √ Content-Type is JSON √ Answers in under 500 ms √ Only category 4, cheapest first └ Create product POST http://localhost:8080/api/v1/products [201 Created, 296B, 8ms] √ Status is 201 √ Location points to the new product √ Saved with the price we sent └ Get product GET http://localhost:8080/api/v1/products/16 [200 OK, 260B, 4ms] √ Status is 200 √ It is the product we created └ Delete product DELETE http://localhost:8080/api/v1/products/16 [204 No Content, 111B, 4ms] √ Status is 204 and the body is empty └ Get deleted product GET http://localhost:8080/api/v1/products/16 [404 Not Found, 291B, 5ms] √ Status is 404 after the delete √ Error uses Problem Details ┌─────────────────────────┬───────────────────┬──────────────────┐ │ │ executed │ failed │ ├─────────────────────────┼───────────────────┼──────────────────┤ │ iterations │ 1 │ 0 │ ├─────────────────────────┼───────────────────┼──────────────────┤ │ requests │ 6 │ 0 │ ├─────────────────────────┼───────────────────┼──────────────────┤ │ test-scripts │ 6 │ 0 │ ├─────────────────────────┼───────────────────┼──────────────────┤ │ prerequest-scripts │ 0 │ 0 │ ├─────────────────────────┼───────────────────┼──────────────────┤ │ assertions │ 14 │ 0 │ ├─────────────────────────┴───────────────────┴──────────────────┤ │ total run duration: 639ms │ ├────────────────────────────────────────────────────────────────┤ │ total data received: 811B (approx) │ ├────────────────────────────────────────────────────────────────┤ │ average response time: 30ms [min: 4ms, max: 141ms, s.d.: 49ms] │ └────────────────────────────────────────────────────────────────┘
What this code does
- Requests run top to bottom: login, list, create, read, delete, and a final read that proves the delete. The run creates and removes its own product, so it can be repeated.
- The summary counts 6 requests and 14 assertions with 0 failed. In the Runner window, the same numbers appear as the Passed and Failed totals.
Keep Run manually, set Iterations (how many times to repeat the whole run) and an optional Delay between requests. The result page lists each request with its status and every test as passed or failed, with totals at the top; click a failed test to see its message. A run you repeat after every change, to prove that what worked yesterday still works, is a regression check.
Order matters, because requests share variables: log in first, then create, then read, update and delete what you created. A good collection also cleans up after itself, so it can run twice in a row with the same result. Postman's free plan limits Collection Runner runs per month in recent versions; Newman, below, has no such limit.
Order of execution
Order a runnable collection
Put the requests in the order the runner must send them.
Running collections from the command line with Newman (the idea)
Newman is Postman's free command-line runner. It runs an exported collection with an exported environment and prints the same requests and test results in the terminal.
Export the collection and the environment, then run both from a terminal with one command. The example shows the exit codes and a JUnit report.
Example 6 · Newman: exit codes and a JUnit report
newman --versionnewman run postman/shoplite-api.postman_collection.json -e postman/local.postman_environment.json --env-var "adminPassword=$SHOPLITE_ADMIN_PASSWORD" --reporters junit --reporter-junit-export results/newman.xmlecho $?newman run postman/shoplite-api.postman_collection.json -e postman/local.postman_environment.json --reporters junit --reporter-junit-export results/newman-no-password.xmlecho $?ls resultsgrep -c "<failure" results/newman-no-password.xml$ newman --version 6.2.3 $ newman run postman/shoplite-api.postman_collection.json -e postman/local.postman_environment.json --env-var "adminPassword=$SHOPLITE_ADMIN_PASSWORD" --reporters junit --reporter-junit-export results/newman.xml $ echo $? 0 $ newman run postman/shoplite-api.postman_collection.json -e postman/local.postman_environment.json --reporters junit --reporter-junit-export results/newman-no-password.xml $ echo $? 1 $ ls results newman-no-password.xml newman.xml $ grep -c "<failure" results/newman-no-password.xml 10
What this code does
- With the password, every test passed and
echo $?printed exit code0. Without it, the run failed and the exit code was1: exactly the signal a CI server uses to mark a build red. --reporters junitprinted nothing on screen and wrote XML files instead; the second report holds the ten failures from Example 4. In PowerShell, read the exit code with$LASTEXITCODEinstead of$?.
Newman needs Node.js; install it once with npm install -g newman, then run newman run postman/shoplite-api.postman_collection.json -e postman/local.postman_environment.json. Postman also offers its own Postman CLI (postman collection run) for the same job. A terminal command can run where nobody clicks buttons: on a build server, after every push, which is called CI (continuous integration). Newman ends with exit code 0 when every test passed and 1 when any failed, so the build turns red on its own. --reporters junit writes a JUnit XML report, a test-result format that CI servers display.
Secrets reach Newman through --env-var, read from an environment variable of the terminal or the CI server, so they never sit in the committed files: --env-var "adminPassword=$SHOPLITE_ADMIN_PASSWORD".
Next step
Check your understanding
12 quick questions