A Postman variable comes from the narrowest scope (local, data, environment, collection, global); chained requests pass values through variables. Values for later requests are stored in pm.collectionVariables or pm.environment, because pm.variables lives only until the end of the request or run. A chain makes requests order-dependent, so each creates its own data or explicitly requires its predecessor.
API · Scripts and checks in Postman
A variable of the same name exists in the collection and the environment. Which value goes into the request?
A collection works on dev, and on stage the same baseUrl variable gives another host. The second request reads {{userId}}, which the first one should have stored, and a literal {{userId}} ends up in the URL. Both stories are about the same thing: a Postman variable lives in a particular scope, and scripts decide where a value goes and who can see it. This lesson covers how scopes override one another, how scripts write and read values, and how a chain of requests follows from that.
How it works and why it is designed so
There are five scopes: global, collection, environment, data and local. Postman substitutes the value from the narrowest scope where the variable is found. So an environment variable overrides a collection one of the same name, and a value from a CSV in the Runner overrides both. The idea is that shared values are set once and a specific run can change them without touching the shared settings. Environments (dev, stage, prod) exist so the same collection runs on different stands just by switching the selected environment.
Which value wins
Figure 1. Reading goes top to bottom: the first scope that has the variable wins.
Scripts add writing to this. In the Pre-request and Post-response tabs (the names current Postman uses; the second used to be called Tests) the pm object has one object per scope: pm.environment, pm.collectionVariables, pm.globals, pm.iterationData (no set) and pm.variables. The last one reads from all scopes but writes to local. Scripts can be set on a collection, a folder and a request: they run in the order collection, folder, request.
Example: a "create, then read" chain
The first request creates a user, the second reads it. A common attempt to store the id with pm.variables.set works only inside a collection run, and a request sent alone does not see the id:
// trap: a local variable lives only until the run ends
pm.variables.set('userId', pm.response.json().id);
// GET {{baseUrl}}/users/{{userId}} sent alone with Send goes out with a literal {{userId}}
A local variable lives until its request ends, or until the run ends in the Collection Runner or Newman. In a run the next request sees it, but a request sent alone with Send gets a literal {{userId}}, and the value is gone after the run. A value that must outlive requests needs a longer-lived scope:
// Post-response of POST {{baseUrl}}/usersconst user = pm.response.json();
pm.test('User is created', () => {
pm.response.to.have.status(201);
pm.expect(user.id).to.be.a('string');
});
// outlives this request: the next ones read {{userId}}
pm.collectionVariables.set('userId', user.id);
The next request uses {{baseUrl}}/users/{{userId}}. The choice between pm.collectionVariables and pm.environment is meaningful: the id of a created user does not depend on the stand, so the collection fits. Values that differ between stands (host, keys) stay in the environment.
Limits and alternatives
A chain through variables has a price: requests become order dependent. Run the second request alone and {{userId}} is empty or stale. So such a request either creates its own data or says in its description that it needs the previous one. For many values per run a data file in the Runner is better. Secrets have their own practices: see the lesson on variable scopes and secrets.
Common mistakes
pm.variables.set for data between requests. It works in the Runner, but a request sent alone gets a literal {{userId}}, and the value is gone after the run;
Same-named variables in several scopes. Values come from not where you expect, and a test on stage takes a dev value. Give variables unique names or check which scope wins;
No environment selected. Environment variables are empty and the request goes to a wrong or empty host;
Stale values. A variable left over from the last run masks a failure: clear it with unset when the data is no longer needed.
Check yourself
A variable host exists in the collection with the value a.test and in the active environment with b.test. Which host does the request use?
Answer
b.test. Environment is narrower than collection and overrides it. If the Runner data row also had host, that one would win.
The first request's post-response does pm.variables.set('id', 5), the second, sent separately with Send, reads {{id}} and gets nothing. Why, and what to change?
Answer
pm.variables writes to the local scope, which outside a collection run lives only until the request ends (in a run, until the run ends). To pass data between requests use pm.collectionVariables.set or pm.environment.set.
Related lessons: “Pre-request, post-response and basic checks”, “Schema validation and a chain of requests”, “Collections, environments and variables”, “Variable scopes and secrets”.
In an interview.Junior: Variables have scopes: a narrower one overrides a wider one. A pre-request script prepares data, a post-response script checks the response and stores values for the next requests. Middle/Senior: The override order is local, data, environment, collection, global. Data between requests goes through collection or environment, because local lives only until the request or run ends and is not kept between runs. A chain makes requests order dependent, so each one either creates its own data or explicitly requires the previous one, and environment specific values (host, keys) stay in the environment.
Pre-request, post-response and basic checks
A pre-request script prepares data before sending (unique values, token, headers); a post-response script checks and stores values after the reply. Each check is a separate pm.test with a clear name, because the first failed expect aborts the test and hides the rest. The status is checked first, since on a non-JSON response json() throws a parse error. Shared logic moves to the collection level.
API · Scripts and checks in Postman
A script must prepare data before the request and check the response after it. Where does each go?
A create-payment test fails with "email already exists" on the second run: the request body kept the same email. And another test, with a status, a field and the response time side by side, shows only the first failure. The right place for a script and the right shape of a test solve both. The lesson covers what runs before the request, what after, and how to write pm.test so that the report shows the cause.
How it works and why it is designed so
A pre-request script runs before sending, when there is no response yet, so that is where data is prepared: unique values, a token, a signature, headers. A post-response script runs after the response, when pm.response exists: that is where you check and store values. Collection, folder and request scripts run in that order, for both tabs. The language is JavaScript, assertions are Chai via pm.expect, and pm.test wraps a group of checks under one name.
When a script runs
Figure 1. The order cannot be swapped: before the request is sent there is no response yet.
Each pm.test gives a separate report row, passed or failed. Inside one test the first failed expect throws, and the remaining checks of that test do not run.
Example: from one big test to several small ones
First a pre-request script that solves the repeated email:
// Pre-request: a unique email for every runconst email = 'qa+' + Date.now() + '@example.com';
pm.variables.set('email', email);
// request body: { "email": "{{email}}" }
Now the post-response script. The "everything in one" version:
// one test: the first failure hides the rest
pm.test('Response is correct', () => {
pm.response.to.have.status(201);
pm.expect(pm.response.json().status).to.eql('pending');
pm.expect(pm.response.responseTime).to.be.below(800);
});
If the server returns 500, the report shows one red test, and whether the field and the time are broken too is unknown. The split version gives a row for every cause:
pm.test('Status 201', () => pm.response.to.have.status(201));
pm.test('Response time < 800 ms', () => {
pm.expect(pm.response.responseTime).to.be.below(800);
});
pm.test('Content-Type is JSON', () => {
pm.expect(pm.response.headers.get('Content-Type'))
.to.include('application/json');
});
const body = pm.response.json();
pm.test('Body fields', () => {
pm.expect(body.status).to.eql('pending');
pm.expect(body.amount).to.be.a('number').and.eql(150);
});
pm.test('Sensitive data is not returned', () => {
pm.expect(body).to.not.have.property('cardNumber');
});
Now the Runner report shows exactly what broke, and the test name is itself a description of the expectation.
Limits and alternatives
Small tests are not free: every pm.response.json() parses the body, so parse once into a variable. If the response is not JSON (an HTML error page from a proxy), json() throws: inside a pm.test the test fails with an unclear parse error, and at the top level of the script, like const body above, the script aborts and the following tests disappear from the report. That is why the first test in a script checks the status. A script that every request needs (a header, a token) goes to the collection or folder level instead of being copied.
Common mistakes
A check in pre-request. There is no response yet and pm.response is unavailable;
One test for everything. The first failure hides the rest, and the name "Response is correct" explains nothing;
A fixed email or name. The second run hits a uniqueness rule on the server. Generate data in pre-request;
Checking only the status. The body, headers and absence of sensitive fields stay unchecked.
Check yourself
A test has three expect calls side by side, and the report says it failed on the first. Were the other two run?
Answer
No. A failed expect throws and aborts the test function. To see every problem in one run, split the checks into separate pm.test calls.
Where do you generate a unique email for the request body: pre-request or post-response, and why?
Answer
In pre-request: the value is needed before sending. In post-response the request has already gone out with whatever was there.
Related lessons: “Postman: variables, scripts, chaining”, “Schema validation and a chain of requests”, “Useful commands and a strong test”, “Common traps in Postman scripts and tests”.
In an interview.Junior: Pre-request prepares data and a token, post-response checks the response and stores values. Each check goes into its own pm.test with a clear name. Middle/Senior: Scripts run collection, folder, request. Small tests are needed because the first failed expect aborts the test and hides the rest. I check the status first because on a non JSON response json() gives a parse error instead of a clear failure, and I move shared logic to the collection level.
Schema validation and a chain of requests
Schema validation with pm.response.to.have.jsonSchema checks the fields and types of the whole response and catches contract drift. Business values are checked by separate tests. additionalProperties: false forbids extra fields, but it is kept only where a leak is a risk, because elsewhere new fields would cause false failures. In a chain, post-response saves the id to a variable after checking the status, and the next request uses it as {{accountId}}.
API · Scripts and checks in Postman
A test checks one field and the backend added an extra one. How do you notice the contract change?
A backend developer added an internalId field to the response and changed amount from a number to the string "150.00". A test that checks body.status stayed green while clients break. Single expect calls only see the fields you looked at. Schema validation looks at the whole structure. The lesson covers what it catches, what it does not, and how to pass a request's result to the next one.
How it works and why it is designed so
pm.response.to.have.jsonSchema(schema) checks the response body against a JSON Schema: required fields, types, allowed values, format. A schema describes the shape of data, not specific values, so one test protects the contract against drift while values are checked by separate tests. The schema is usually taken from the OpenAPI specification rather than written by hand, so it does not diverge from the documentation.
Example: a schema that catches an extra field and a type change
const schema = {
type: 'object',
required: ['id', 'status', 'amount', 'currency'],
properties: {
id: { type: 'string' },
status: { enum: ['pending', 'completed', 'failed'] },
amount: { type: 'number', exclusiveMinimum: 0 },
currency: { type: 'string', pattern: '^[A-Z]{3}$' },
},
additionalProperties: false, // an extra field = a failed test
};
pm.test('Schema is valid', () => {
pm.response.to.have.jsonSchema(schema);
});
A response with amount: "150.00" now fails on the type, and a response with internalId fails on additionalProperties: false. The report names the path to the field, so the cause is visible without debugging. It also protects against leaking internal fields.
A chain of requests
The result of the first request goes to the next one through a variable: stored in post-response, substituted as {{accountId}}.
A chain of two requests
Figure 1. Data between requests goes through a variable, not by hand.
// Post-response of POST /accountsif (pm.response.code === 201) {
pm.environment.set('accountId', pm.response.json().id);
}
// Post-response of the last request in the folder: clean up
pm.environment.unset('accountId');
Note the unset at the end: without it the next run starts with someone else's id.
Limits and alternatives
additionalProperties: false cuts both ways: a new optional field is usually not a breaking change, yet the test rejects it. Turn it on where the response composition is strict or there is a leak risk, and elsewhere allow extra fields. A schema does not check business values: amount: 1 instead of 150 passes. It also describes only the body, so status and headers are checked separately. For big contracts keep the schema in one place and validate with ajv in code, as in the lesson on schema validation.
Common mistakes
A schema written "to fit the response". It was generated from the current response, so it confirms any defect. Take it from the contract;
A leftover id. The variable stayed from the last run and the next request works with someone else's data;
A chain without checking each step. The first request failed and the next ones hurry on with an empty {{accountId}} and give confusing failures. Check the status before storing the id;
A schema instead of values. It does not see a wrong amount or status.
Check yourself
The server returned amount: "150" instead of 150, and the test checks only pm.expect(body.amount).to.eql(150). It will fail. How does a schema help more here?
Answer
A value test fails only on this field. A schema checks all fields at once: types, required, extra keys. So it catches drift in the fields nobody wrote a separate expect for.
When does additionalProperties: false hurt rather than help?
Answer
When the API evolves by adding fields: a new optional field does not break clients, yet the test goes red. There it is better to allow extra fields and keep the strict schema for sensitive responses.
Related lessons: “Pre-request, post-response and basic checks”, “Useful commands and a strong test”, “Schema validation in code: ajv and zod”, “Collection Runner and data-driven tests”.
In an interview.Junior: A schema checks the whole structure of a response: fields, types, values. additionalProperties: false catches extra fields. I pass data between requests through variables: store the id in post-response and use {{accountId}}. Middle/Senior: A schema catches contract drift but not business values, so it is complemented with value tests. I keep the strict ban on extra fields where there is a leak risk, since otherwise additive changes cause false failures. In a chain I check the status before storing the id and clean up the variables so runs do not depend on each other.
Useful commands and a strong test
A strong test fails for every plausible breakage: code, structure, value and side effect, so checking only status 200 is not enough. The minimum is the status, the schema and key values taken from what was sent, plus a GET after a write. Useful commands are pm.sendRequest for a helper request, pm.execution.setNextRequest for the Runner order and console.log for debugging in the Postman Console.
API · Scripts and checks in Postman
A test checks only the 200 code and is green. What else could the backend have broken?
PATCH /accounts/42 renaming an account returns 200. The test is green. A week later it turns out the backend wrote the name into the wrong field and wiped the currency: the endpoint behaved like PUT. Status 200 only says the server processed something without an error. The lesson covers why such a test is weak, what to add, and which script commands help check and debug.
How it works and why it is designed so
A test is strong when it fails for any plausible breakage. Breakages are of four kinds: code (a server error), structure (a field vanished or changed type), value (the wrong thing was written) and side effect (something extra was touched or nothing was saved). Status covers only the first. So the minimum for a response is status, schema and key values. A write adds a following GET, because the PATCH response shows what the server says, and the GET shows what is really stored.
A weak and a strong test
Typical
Only status 200
An empty array or a wrong value passes: the test is green, the defect stays.
Better
Status, schema, values, GET
After a write a GET too: you see what was saved and what was not touched.
Figure 1. Checking only the response code guarantees almost nothing.
Example: a weak script, what it misses, a strong script
It misses: a name written into another field; a response without the required id; a cardNumber field that started coming back; a new name that exists only in the response and not in the database. The strong version:
const schema = { type: 'object', required: ['id', 'name'] };
1pm.test('Status 200', () => pm.response.to.have.status(200));
const body = pm.response.json();
pm.test('Name changed to the sent value', () => {
2 pm.expect(body.name).to.eql(pm.variables.get('newName'));
});
pm.test('Schema is valid', () => {
3 pm.response.to.have.jsonSchema(schema);
});
pm.test('No card data in the response', () => {
4 pm.expect(body).to.not.have.any.keys('cardNumber', 'cvv');
});
The status is needed, but it is only the entrance ticket.
A value check that the sent value was actually saved.
The schema catches drift in structure and types.
A negative check that nothing sensitive leaks.
The newName value was set in pre-request via pm.variables.set and is available in the post-response of the same request and, within a collection run, in the following requests. Then the next request of the run re-reads the resource:
// Post-response of GET /accounts/42, the next requestconst acc = pm.response.json();
pm.test('Name was persisted', () => {
pm.expect(acc.name).to.eql(pm.variables.get('newName'));
});
pm.test('The other fields are untouched', () => {
pm.expect(acc.currency).to.eql(pm.environment.get('currencyBefore'));
});
This checks both what was written and that the other fields stayed as they were. The currencyBefore value was stored by an earlier GET.
Commands that help
pm.sendRequest(...): a helper request from a script, for example fetching a token in pre-request;
pm.execution.setNextRequest('Name'): changes the order in the Runner, null stops the run. Old collections use postman.setNextRequest;
pm.environment.unset('token'): remove a variable after yourself;
console.log(...): output to the Postman Console, which shows the raw request and response. It is the main debugging tool: it shows the final URL and headers, so you see at once whether {{token}} went out literally.
Limits and alternatives
A strong test does not mean "more checks at any price". Checking every field duplicates the schema and breaks on every harmless change. Choose by risk: money, permissions, persistence. What is hard to check through the response (an event in a queue, an email, an audit entry) is checked another way: a separate request or a direct query to the store. For big suites, queues and complex data, code (Playwright, REST Assured) fits better, with real functions and types.
Common mistakes
Only 200. The test is green on an empty or wrong response;
Checking a write only by its response. A PATCH response does not prove the data was saved;
An expected value taken from the response.expect(body.name).to.eql(body.name) is always green: take the value from what was sent;
Ignoring the Console. People spend hours searching for a cause visible in the raw request.
Check yourself
A test after PATCH checks status 200 and that body.name equals the sent value. Which breakage does it still miss?
Answer
Those not visible in the response: the data was not saved in the store, other fields were wiped, the response was assembled bypassing the database. A following GET catches them.
A request failed with 401 and the URL in the Console looks fine. Where to look next?
Answer
At the headers in the same Console: is there an Authorization and does it hold a real token and not a literal {{token}}. Then the variable scope and the token's validity.
Related lessons: “Pre-request, post-response and basic checks”, “Schema validation and a chain of requests”, “pm.* in practice: a reference and working patterns”, “Common traps in Postman scripts and tests”.
In an interview.Junior: A test that checks only 200 guarantees almost nothing. I check the status, the schema and the key values, and after a write I do a GET to confirm that the change was saved. Middle/Senior: A test is strong when it fails on every plausible breakage: code, structure, value, side effect. I take expectations from what was sent and not from the response, and choose the depth of checks by risk so as not to duplicate the schema. What the response does not show, I check with a separate request.
pm.* in practice: a reference and working patterns
The pm object is a script's single entry point to the request, the response and variables of every scope. A token is refreshed by a collection-level script only when it is about to expire, not before every request: the token and its expiry live in variables with a margin, and the helper pm.sendRequest is asynchronous. Polling is built with an attempt counter and an exit so the run cannot hang.
API · Scripts and checks in Postman
A Postman token is refreshed only when needed, not before every request. Which script does that?
A collection of 80 requests calls the authorisation endpoint before each one. The server log is full of tokens and login limits run out. The other extreme: the token is entered by hand and expires mid-run. A script that refreshes the token only when it is really needed fixes both. The lesson gathers a reference of the pm object and four working patterns.
How it works: a pm reference
The pm object is the single entry point to the request, the response and variables:
pm.request: URL, method, headers and body of the current request. In pre-request they can be changed, for example pm.request.headers.upsert({ key: 'X-Trace-Id', value: pm.variables.replaceIn('{{$guid}}') });
pm.variables, pm.environment, pm.collectionVariables, pm.globals, pm.iterationData: scope variables with get, set, unset (pm.iterationData has no set);
pm.info: the request name, the iteration number;
pm.sendRequest: a helper HTTP request from a script, asynchronous;
pm.execution.setNextRequest: the order in the Runner and Newman.
Pattern 1. A token refreshed only when needed
The token and its expiry time live in variables, and the helper request goes out only if less than the reserve remains.
Refreshing a token on demand
Figure 1. The helper request goes out only when the token is close to expiry.
A 30 second reserve protects against expiry in the middle of a request. The helper call is asynchronous: Postman waits for the callback to finish before sending the main request, so the callback's value is available to it. The current docs also show const res = await pm.sendRequest(...): then the code after the call waits for the response. The script sits at the collection level so it works for every request.
Pattern 2. Unique data
pm.variables.replaceIn('{{$randomEmail}}') returns the value of a dynamic variable right in the script, so a unique email or key can be put into your own variable and reused in later requests.
Pattern 3. Polling an asynchronous operation with a limit
The operation returns 202 and the result appears later:
// Post-response: polling an operation that returned 202const tries = Number(pm.variables.get('tries') || 0) + 1;
pm.variables.set('tries', tries);
const status = pm.response.json().status;
if (status !== 'done' && tries < 10) {
pm.execution.setNextRequest(pm.info.requestName);
} else {
pm.variables.set('tries', 0);
pm.test('The operation finished', () => {
pm.expect(status).to.eql('done');
});
}
The counter and the exit are mandatory: without them the loop could run forever. Also setNextRequest without a pause floods the service with requests, so a real run needs a delay between attempts. setNextRequest works in the Collection Runner and Newman, and does nothing in a single run from the request window.
Pattern 4. Signing a request. For HMAC a script uses the built-in Web Crypto (crypto.subtle.importKey with HMAC/SHA-256 and crypto.subtle.sign), and the hex result goes into a header. The secret comes from a variable, not from the code.
Limits and alternatives
A collection script runs for every request, so long computations and extra pm.sendRequest calls there slow everything down: add a condition, as in the token pattern. Complex logic in Postman is hard to test and version. If scripts grow, they ask for code with unit tests. Often the token can be obtained without a script: the built-in OAuth 2.0 authorisation type refreshes a token itself, but only when the server issued a refresh token (client credentials usually has none), and not in Newman, the Postman CLI or monitors.
Common mistakes
A token before every request. Extra load and noise in the authorisation logs;
Using data from a pm.sendRequest response outside the callback. The code after the call runs earlier, the value is not there yet;
A loop without an attempts limit. The run never ends;
A secret in console.log. It lands in Newman logs and CI artefacts.
Check yourself
The 30 s reserve was removed from the token pattern and it compares Date.now() > exp. What new breakage becomes possible?
Answer
The token can expire between the check and the server handling the request: the script considered it valid and the server already answered 401. The reserve covers network delay and clock skew.
Why does the polling pattern need both a counter and the else exit?
Answer
The counter limits the attempts, and the else branch resets it and does the check. Without a reset the next iteration of the same run starts with the accumulated value, and without a limit the loop does not end if the operation hangs.
Related lessons: “Useful commands and a strong test”, “Common traps in Postman scripts and tests”, “The token automatically and what to check”, “Collection Runner and data-driven tests”.
In an interview.Junior: The pm object gives access to the request, the response and variables. I refresh the token with a script only when it is about to expire, not before every request. Middle/Senior: I keep the token and its expiry in variables with a reserve, and make the helper request through the asynchronous pm.sendRequest: I read its value in the callback or via await, never on the line after a call without await. I build polling with a counter and an exit so the run does not hang. If script logic grows, I move it into code with tests.
Common traps in Postman scripts and tests
Most Postman traps follow from three sandbox properties. A test in pm.test fails only on an exception, calls such as pm.sendRequest are asynchronous, and variables live in different scopes. So an expression without pm.expect is always green, and a literal {{userId}} in a URL means the variable is missing from the active scope. A new test is not trusted until it has turned red on deliberately wrong data.
API · Scripts and checks in Postman
The URL contained a literal {{userId}} and the test is green on a wrong response. Why?
The collection passed green, yet in production payments hang in the failed status. It turned out the "Status is paid" test could never fail. Most "weird" Postman failures are a few identical traps: a variable in the wrong place, a test without an assertion, an async callback, a string instead of a number. The lesson covers the symptom, the cause and the action for each, and the order of debugging.
How it works and why it is designed so
Three properties of the sandbox produce most problems. First: pm.test fails only when an exception is thrown inside, and a plain expression throws nothing. Second: pm.sendRequest and similar calls are asynchronous, so without await the code after the call does not wait. Third: Postman variables are stored as strings and live in different scopes with different lifetimes. Knowing this, a symptom is easy to trace to a cause.
A test that cannot fail
Wrong
An expression without expect
The comparison returns false and nobody throws: the test is green even on failed.
Right
pm.expect(...).to.eql
A mismatch throws and the test fails with an explanation.
Figure 1. Without pm.expect a comparison checks nothing.
This test passes even with status: "failed": the expression returns false and that is it. After:
pm.test('Status is paid', () => {
pm.expect(pm.response.json().status).to.eql('paid');
});
The pm.expect(...) call throws on a mismatch, and the report shows the expected and received values. Check through pm.expect or pm.response.to.... A useful habit: to trust a new test, deliberately break the expectation once and make sure it goes red.
What a red test looks like in Newman
❏ Orders
↳ Pay order
1POST https://stage.shop.test/v1/orders/17/pay [200 OK, 412B, 143ms]
1. Status is paid
# failure detail
2 1. AssertionError Status is paid
3expected 'failed' to deeply equal 'paid'
at assertion:0 in test-script
4 inside "Orders / Pay order"
Response status: 200 is only about transport. The business status of the payment is in the body.
What failed:AssertionError with the test name: the check really threw an exception.
Expected and received: received failed, expected paid. A test without pm.expect would never print this line.
Where: the request and its folder in the collection.
What to do
Open the response of this request and find out why the payment is failed. The test is right: red here is a finding, not noise.
Figure 2. A failed pm.expect test in Newman output (shortened): the numbers lead to the explanations.
Traps: symptom, cause, action
A literal {{userId}} in the URL. The variable is not in the active environment, no environment is selected, or the previous request did not set it. Open the Console: it shows the final URL. Check the scope and the order of requests;
The asynchrony of pm.sendRequest. The code after the call runs before the callback. Store the value inside the callback:
let ref;
pm.sendRequest(url, (err, res) => {
ref = res.json().id; // runs later
});
pm.variables.set('ref', ref); // ref is still undefined here
Types. Postman variables are stored as strings, and quoted CSV values stay strings (Newman converts only unquoted numbers). Comparing eql(200) with the string '200' fails. Convert with Number();
Scope overriding. The narrower scope wins, so a token in pm.environment can hide behind a local variable of the same name. Check where the value comes from;
Secrets in logs. A console.log of a token or personal data lands in Newman logs and CI artefacts. Log identifiers, not secrets;
Order and foreign data dependence. A hard coded userId: 42 breaks when the data is gone. A test should create what it needs and clean up;
A heavy collection script. It runs for every request: add a condition for when it is really needed.
The order of debugging
From symptom to cause
Figure 3. First see what went out, then where the value came from, then rule out the surroundings.
Limits and alternatives
Discipline removes part of the traps: unique variable names, creating data in the test itself, linting scripts in the repository. If a collection grows and traps multiply, that is a signal that tests are better written in code with types and a safe CI. For the scripts themselves it helps to run the collection through Newman and check that it goes red on known bad data.
Check yourself
The test pm.test('ok', () => { pm.response.code === 200; }) is green on a 500 response. Why, and how to fix it?
Answer
The expression returns false but throws nothing, and pm.test fails only on an exception. The fix: pm.expect(pm.response.code).to.eql(200) or pm.response.to.have.status(200).
A value from a pm.sendRequest response was written to a variable after the call, and it is empty in the request. What is wrong?
Answer
The callback runs later than the line after the call, so the write happens before the value exists. Write inside the callback.
Related lessons: “Useful commands and a strong test”, “pm.* in practice: a reference and working patterns”, “Variable scopes and secrets”, “Postman: variables, scripts, chaining”.
In an interview.Junior: Typical traps: a variable in the wrong scope, a test without pm.expect that is always green, the asynchrony of pm.sendRequest, strings instead of numbers. I debug with the Postman Console. Middle/Senior: Most traps follow from three properties: pm.test fails only on an exception, calls are asynchronous, variables are strings in different scopes. I do not trust a new test until I see it go red on deliberately wrong data. I do not log secrets because they end up in CI artefacts.