0
0
Postmantesting~15 mins

Script execution order in Postman - Deep Dive

Choose your learning style9 modes available
Overview - Script execution order
What is it?
Script execution order in Postman defines the sequence in which scripts run during an API request. Postman allows scripts to run before a request (Pre-request scripts) and after a response (Tests). These scripts help automate tasks like setting variables or checking responses. Understanding the order helps you control test flow and data setup.
Why it matters
Without knowing script execution order, tests may fail or behave unpredictably because setup steps run too late or checks run too early. This can cause wasted time debugging and unreliable API testing. Proper order ensures your tests are accurate and your automation works smoothly, saving effort and increasing confidence in your APIs.
Where it fits
Before learning script execution order, you should understand basic Postman concepts like requests, collections, and environment variables. After mastering execution order, you can explore advanced scripting, chaining requests, and continuous integration with Postman.
Mental Model
Core Idea
Postman scripts run in a fixed sequence: first Pre-request scripts, then the request sends, and finally Test scripts after the response arrives.
Think of it like...
It's like cooking a meal: you prepare ingredients first (Pre-request scripts), then cook the dish (sending the request), and finally taste and adjust seasoning (Test scripts) after cooking.
┌───────────────────────┐
│ 1. Pre-request Script │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│ 2. Send Request       │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│ 3. Receive Response   │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│ 4. Test Script        │
└───────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Postman Scripts
🤔
Concept: Postman allows scripts to run before and after requests to automate tasks.
Postman scripts are small pieces of JavaScript code. Pre-request scripts run before sending the API request. Test scripts run after receiving the response. These scripts can set variables, check response data, or log information.
Result
You can automate setup and validation steps around API calls.
Knowing that scripts exist before and after requests is the base for controlling test flow.
2
FoundationTypes of Scripts in Postman
🤔
Concept: There are two main script types: Pre-request and Test scripts.
Pre-request scripts prepare data or environment before the request. Test scripts verify the response after the request. Both scripts can access and modify variables and use Postman API methods.
Result
You can organize your automation into setup and verification phases.
Separating setup and verification helps keep tests clear and maintainable.
3
IntermediateExecution Order Within a Single Request
🤔Before reading on: do you think Test scripts run before or after the request is sent? Commit to your answer.
Concept: Scripts run in a strict order: Pre-request scripts first, then the request sends, then Test scripts run after response.
When you run a request, Postman first executes all Pre-request scripts. Then it sends the HTTP request to the server. After the server responds, Postman runs the Test scripts to check the response.
Result
Scripts run predictably so setup happens before sending, and checks happen after receiving.
Understanding this order prevents timing bugs where tests run before data is ready.
4
IntermediateCollection and Folder Script Execution
🤔Before reading on: do you think folder-level scripts run before or after request-level scripts? Commit to your answer.
Concept: Scripts can be set at collection, folder, and request levels, and they run in a defined sequence.
When running a request inside a folder and collection, Pre-request scripts run in this order: collection Pre-request scripts, folder Pre-request scripts, then request Pre-request scripts. After the response, Test scripts run in reverse order: request Test scripts, folder Test scripts, then collection Test scripts.
Result
Scripts at higher levels run first for setup and last for tests, allowing shared setup and checks.
Knowing this hierarchy helps organize reusable scripts and avoid conflicts.
5
IntermediateAsynchronous Behavior in Scripts
🤔Before reading on: do you think Postman waits for asynchronous code in scripts before continuing? Commit to your answer.
Concept: Postman scripts run synchronously, but asynchronous code like setTimeout or fetch may not complete before the request sends or tests run.
If you use asynchronous JavaScript in scripts, Postman does not wait for it to finish. This can cause variables not to be set in time or tests to run too early. To handle async tasks, use Postman's pm.sendRequest or chain requests instead.
Result
Scripts behave synchronously, so async code needs special handling.
Understanding sync execution avoids subtle bugs with timing and data availability.
6
AdvancedChaining Requests Using Script Execution Order
🤔Before reading on: do you think you can trigger another request from a Test script? Commit to your answer.
Concept: You can chain requests by setting variables in Pre-request or Test scripts and controlling execution flow.
By setting environment or collection variables in Test scripts, you can influence subsequent requests. For example, a Test script can save a token from a response, which a later Pre-request script uses to authenticate. This chaining relies on the script execution order to prepare data before requests.
Result
You can build complex workflows where requests depend on previous responses.
Mastering script order enables powerful automated API testing scenarios.
7
ExpertUnexpected Script Execution Pitfalls
🤔Before reading on: do you think scripts in the Postman Collection Runner run in the same order as in the app? Commit to your answer.
Concept: Script execution order can differ subtly in Collection Runner or Newman, causing unexpected behavior.
In Collection Runner and Newman (Postman's CLI), scripts run in the same logical order but timing and environment resets can cause variables to reset or scripts to behave differently. Also, scripts that rely on asynchronous code or external APIs may fail silently. Understanding these differences is key for reliable automation.
Result
Tests that pass in the app may fail in automation without careful script design.
Knowing environment and runner differences prevents costly test failures in CI/CD pipelines.
Under the Hood
Postman runs scripts using a JavaScript engine embedded in the app. When a request runs, Postman first executes all Pre-request scripts synchronously in the order: collection, folder, request. Then it sends the HTTP request. After receiving the response, it runs Test scripts in reverse order: request, folder, collection. Variables and context are shared and updated between scripts. Asynchronous JavaScript does not pause script execution, so Postman continues immediately after synchronous code finishes.
Why designed this way?
This design ensures predictable setup before requests and validation after responses. Running scripts in hierarchical order allows reuse and overrides at different levels. Synchronous execution simplifies script management and reduces complexity. Asynchronous support is limited to avoid unpredictable timing issues. Alternatives like fully async scripts would complicate test flow and increase errors.
┌───────────────────────────────┐
│ Collection Pre-request Script  │
├───────────────────────────────┤
│ Folder Pre-request Script      │
├───────────────────────────────┤
│ Request Pre-request Script     │
├───────────────────────────────┤
│ Send HTTP Request             │
├───────────────────────────────┤
│ Request Test Script            │
├───────────────────────────────┤
│ Folder Test Script             │
├───────────────────────────────┤
│ Collection Test Script         │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think Test scripts run before the request is sent? Commit to yes or no.
Common Belief:Test scripts run before the request is sent to prepare data.
Tap to reveal reality
Reality:Test scripts run only after the response is received, never before the request.
Why it matters:Running tests too early means no response data is available, causing false failures.
Quick: Do you think asynchronous code in scripts pauses Postman execution? Commit to yes or no.
Common Belief:Postman waits for all asynchronous code in scripts to finish before continuing.
Tap to reveal reality
Reality:Postman does not wait for asynchronous code like setTimeout or fetch to complete in scripts.
Why it matters:Assuming async code finishes can cause variables to be unset or tests to run too early, leading to flaky tests.
Quick: Do you think folder-level scripts override request-level scripts? Commit to yes or no.
Common Belief:Folder-level scripts replace request-level scripts if both exist.
Tap to reveal reality
Reality:Folder-level scripts run before (Pre-request) or after (Test) request-level scripts; they do not override but complement them.
Why it matters:Misunderstanding this can cause duplicated or missing setup and checks, confusing test results.
Quick: Do you think script execution order is the same in Postman app and Newman CLI? Commit to yes or no.
Common Belief:Scripts run identically in Postman app and Newman CLI.
Tap to reveal reality
Reality:While order is logically the same, environment resets and timing differences can cause scripts to behave differently.
Why it matters:Tests passing in the app may fail in automation pipelines, causing unexpected CI/CD failures.
Expert Zone
1
Pre-request scripts at collection level run before folder and request scripts, allowing global setup but can be overridden by lower levels.
2
Test scripts run in reverse order to Pre-request scripts, enabling layered validation from specific to general.
3
Asynchronous code in scripts can cause silent failures; using pm.sendRequest is the recommended way to handle async calls within scripts.
When NOT to use
Avoid relying on asynchronous JavaScript like fetch or setTimeout in scripts because Postman does not wait for them. Instead, use pm.sendRequest or chain requests with variables. For complex workflows, consider external test runners or CI/CD tools that support async better.
Production Patterns
In real projects, teams use collection-level Pre-request scripts to set authentication tokens globally, folder-level scripts for environment-specific setup, and request-level scripts for fine-grained checks. Chaining requests by saving response data in variables is common for testing multi-step APIs. Scripts are designed to be idempotent and fast to run in CI pipelines.
Connections
Event Loop in JavaScript
Builds-on
Understanding Postman's synchronous script execution relates to how JavaScript's event loop handles asynchronous tasks, explaining why async code in scripts doesn't pause execution.
Continuous Integration (CI) Pipelines
Builds-on
Knowing script execution order helps design reliable API tests that run smoothly in CI pipelines, preventing flaky tests and build failures.
Cooking Recipe Process
Analogy
The step-by-step nature of script execution mirrors cooking stages, highlighting the importance of order in preparing, cooking, and tasting for a successful meal.
Common Pitfalls
#1Using asynchronous JavaScript without handling in scripts.
Wrong approach:setTimeout(() => { pm.environment.set('token', 'abc123'); }, 1000);
Correct approach:pm.environment.set('token', 'abc123'); // synchronous setting
Root cause:Misunderstanding that Postman does not wait for async callbacks, so variables may not be set in time.
#2Placing Test scripts expecting response data before sending the request.
Wrong approach:pm.test('Response has status 200', () => { pm.response.to.have.status(200); }); // in Pre-request script
Correct approach:pm.test('Response has status 200', () => { pm.response.to.have.status(200); }); // in Test script
Root cause:Confusing Pre-request and Test script roles, causing tests to run without response data.
#3Assuming folder-level scripts override request-level scripts.
Wrong approach:Only writing folder Pre-request scripts and expecting request scripts not to run.
Correct approach:Writing both folder and request Pre-request scripts, knowing they run in order.
Root cause:Misunderstanding script hierarchy and execution order.
Key Takeaways
Postman runs scripts in a strict order: Pre-request scripts before sending requests, Test scripts after receiving responses.
Scripts can be set at collection, folder, and request levels, running in a defined hierarchical sequence.
Postman executes scripts synchronously and does not wait for asynchronous JavaScript to finish.
Understanding script execution order is essential for reliable API testing and automation.
Misusing script order or async code causes flaky tests and debugging headaches, especially in automation pipelines.