Bird
Raised Fist0
Postmantesting~15 mins

Tests tab and pm.test() in Postman - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Tests tab and pm.test()
What is it?
In Postman, the Tests tab is where you write scripts to check if your API responses are correct. The pm.test() function lets you create individual test cases by giving each a name and a check to run. These tests run automatically after a request and help you verify your API works as expected. This makes it easy to catch errors early and keep your API reliable.
Why it matters
Without tests in Postman, you would have to check API responses manually, which is slow and error-prone. Automated tests save time and catch bugs before they reach users. They also help teams work together by clearly showing what each API should do. Without pm.test() and the Tests tab, ensuring API quality would be much harder and less consistent.
Where it fits
Before learning Tests tab and pm.test(), you should understand how to send requests and read responses in Postman. After mastering tests, you can learn about scripting with pm.response and chaining requests for advanced API workflows. This topic fits into the journey of API testing and automation.
Mental Model
Core Idea
pm.test() lets you write named checks that automatically verify API responses after each request.
Think of it like...
It's like having a checklist for a recipe where each step is checked off to make sure the dish turns out right every time.
┌───────────────┐
│   Postman     │
│  Request sent │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  Response     │
│  received     │
└──────┬────────┘
       │
       ▼
┌─────────────────────────────┐
│ Tests tab runs pm.test()     │
│ - Each test has a name       │
│ - Each test runs a check     │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Test results: Pass / Fail    │
└─────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Postman Tests Tab
🤔
Concept: The Tests tab is where you write scripts to check API responses after a request.
In Postman, after you send a request, you can switch to the Tests tab to write JavaScript code. This code runs automatically after the response arrives. It helps you check if the response data matches what you expect, like status codes or specific values.
Result
You get immediate feedback if your API response meets your expectations or not.
Knowing where and how to write tests in Postman is the first step to automating API validation.
2
FoundationBasics of pm.test() Function
🤔
Concept: pm.test() defines a single test with a name and a check function.
pm.test('Test name', function () { // your check here }); Inside the function, you write assertions to verify response details. For example, checking if the status code is 200: pm.test('Status code is 200', () => { pm.response.to.have.status(200); });
Result
The test runs after the request and shows pass or fail in the test results panel.
Understanding pm.test() is key to organizing your checks into clear, named tests that help identify issues quickly.
3
IntermediateWriting Multiple Tests in Tests Tab
🤔Before reading on: Do you think multiple pm.test() calls run independently or stop after the first failure? Commit to your answer.
Concept: You can write many pm.test() calls to check different parts of the response separately.
Example: pm.test('Status code is 200', () => { pm.response.to.have.status(200); }); pm.test('Response has userId', () => { const jsonData = pm.response.json(); pm.expect(jsonData).to.have.property('userId'); }); Each test runs independently and reports pass or fail separately.
Result
You see a list of test results, each named and marked pass or fail, helping pinpoint exactly what failed.
Knowing tests run independently helps you write thorough checks without one failure hiding others.
4
IntermediateUsing Assertions Inside pm.test()
🤔Before reading on: Do you think assertions inside pm.test() throw errors or just return true/false? Commit to your answer.
Concept: Assertions inside pm.test() use pm.expect() to check conditions and throw errors if they fail, marking the test as failed.
Example assertion: pm.test('Response time is less than 500ms', () => { pm.expect(pm.response.responseTime).to.be.below(500); }); If the condition is false, the test fails and shows an error message.
Result
Tests clearly show which checks failed and why, making debugging easier.
Understanding that assertions throw errors explains how pm.test() knows when a test fails.
5
AdvancedDynamic Tests Based on Response Data
🤔Before reading on: Can pm.test() create tests dynamically based on response content? Commit to your answer.
Concept: You can write pm.test() calls inside loops or conditions to create tests dynamically depending on response data.
Example: const jsonData = pm.response.json(); jsonData.items.forEach((item, index) => { pm.test(`Item ${index} has id`, () => { pm.expect(item).to.have.property('id'); }); }); This creates a test for each item in the response array.
Result
Test results show individual checks for each item, helping find exactly which data is missing or wrong.
Knowing you can generate tests dynamically allows flexible and detailed validation of complex responses.
6
ExpertHandling Async Code in pm.test()
🤔Before reading on: Do you think pm.test() supports async/await for asynchronous checks? Commit to your answer.
Concept: pm.test() supports async functions, letting you write asynchronous tests using async/await syntax.
Example: pm.test('Async test example', async () => { const data = await someAsyncFunction(); pm.expect(data).to.equal('expected'); }); This is useful when tests depend on asynchronous operations like reading files or calling other APIs.
Result
Tests can handle asynchronous logic cleanly without callback hell or timing issues.
Understanding async support in pm.test() unlocks advanced testing scenarios involving asynchronous workflows.
Under the Hood
When a request finishes, Postman runs the script in the Tests tab. Each pm.test() call registers a named test with a function. Postman executes these functions in order. Inside each, assertions using pm.expect() check conditions. If an assertion fails, it throws an error caught by Postman, marking that test as failed. Postman collects all results and displays them in the UI. Async pm.test() functions are awaited before moving on, ensuring proper sequencing.
Why designed this way?
Postman designed pm.test() to be simple and modular, letting users write many small tests with clear names. This approach makes debugging easier because each test isolates one check. Using JavaScript and the Chai assertion library (pm.expect) leverages familiar syntax for developers. Async support was added later to handle modern API testing needs involving asynchronous operations.
┌───────────────┐
│ Request sent  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Response      │
│ received      │
└──────┬────────┘
       │
       ▼
┌─────────────────────────────┐
│ Tests tab script runs        │
│ ┌─────────────────────────┐ │
│ │ pm.test('name', func)   │ │
│ │ ┌─────────────────────┐ │ │
│ │ │ Assertions run       │ │ │
│ │ │ (pm.expect checks)   │ │ │
│ │ └─────────────────────┘ │ │
│ └─────────────────────────┘ │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Test results collected       │
│ Pass / Fail shown in UI      │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does pm.test() stop running other tests if one fails? Commit to yes or no.
Common Belief:If one pm.test() fails, the rest of the tests stop running.
Tap to reveal reality
Reality:All pm.test() calls run independently; one failure does not stop others from running.
Why it matters:Believing tests stop early can cause missed errors and false confidence in API correctness.
Quick: Do pm.test() assertions return true/false or throw errors on failure? Commit to your answer.
Common Belief:Assertions inside pm.test() return true or false to indicate pass or fail.
Tap to reveal reality
Reality:Assertions throw errors when they fail, which pm.test() catches to mark the test as failed.
Why it matters:Misunderstanding this can lead to writing tests that silently fail or don't report errors properly.
Quick: Can pm.test() run asynchronous code using async/await? Commit to yes or no.
Common Belief:pm.test() cannot handle asynchronous code and only works with synchronous checks.
Tap to reveal reality
Reality:pm.test() supports async functions, allowing asynchronous tests with async/await syntax.
Why it matters:Not knowing this limits test complexity and prevents testing APIs that require async workflows.
Quick: Does pm.test() automatically retry failed tests? Commit to yes or no.
Common Belief:pm.test() retries failed tests automatically to confirm failures.
Tap to reveal reality
Reality:pm.test() runs tests once per request; retries must be handled externally.
Why it matters:Expecting automatic retries can cause confusion when intermittent failures appear without explanation.
Expert Zone
1
pm.test() functions run in the order they appear, but their results are collected asynchronously, so test order should not be relied on for side effects.
2
Using descriptive test names in pm.test() is crucial for maintainability and debugging in large test suites.
3
Async pm.test() functions must be properly awaited; forgetting async/await can cause tests to pass incorrectly or behave unpredictably.
When NOT to use
pm.test() is not suitable for load or performance testing where many requests run in parallel; specialized tools like JMeter or k6 are better. Also, for complex test orchestration across multiple APIs, dedicated test frameworks or CI pipelines are preferable.
Production Patterns
In real projects, pm.test() is used to create comprehensive API validation suites that run automatically in CI/CD pipelines. Tests are grouped by feature, use environment variables for flexibility, and include dynamic tests for data-driven validation. Async tests handle chained API calls and external dependencies.
Connections
Unit Testing Frameworks
pm.test() is similar to unit test functions in frameworks like Jest or Mocha.
Understanding pm.test() helps grasp how automated tests are structured in many programming environments.
Continuous Integration (CI)
Tests written with pm.test() can be integrated into CI pipelines to automate API quality checks.
Knowing how pm.test() works enables smooth automation of API testing in software delivery workflows.
Quality Control in Manufacturing
Both pm.test() and manufacturing QC use systematic checks to catch defects early.
Recognizing this connection shows how testing principles apply broadly to ensure quality in different fields.
Common Pitfalls
#1Writing pm.test() without assertions inside the function.
Wrong approach:pm.test('Check status code', () => { // forgot assertion here });
Correct approach:pm.test('Check status code', () => { pm.response.to.have.status(200); });
Root cause:Beginners may forget to include actual checks inside pm.test(), causing tests to always pass without verifying anything.
#2Using synchronous code inside pm.test() when async operations are needed.
Wrong approach:pm.test('Async check', () => { const data = fetchData(); // returns a promise pm.expect(data).to.exist; });
Correct approach:pm.test('Async check', async () => { const data = await fetchData(); pm.expect(data).to.exist; });
Root cause:Misunderstanding async behavior leads to tests that don't wait for promises, causing false positives.
#3Assuming pm.test() stops running after a failure.
Wrong approach:pm.test('Test 1', () => { pm.expect(false).to.be.true; }); pm.test('Test 2', () => { pm.expect(true).to.be.true; }); // This test is skipped (wrong assumption)
Correct approach:pm.test('Test 1', () => { pm.expect(false).to.be.true; }); pm.test('Test 2', () => { pm.expect(true).to.be.true; }); // Both tests run independently
Root cause:Beginners often think one failure stops all tests, missing other errors.
Key Takeaways
The Tests tab in Postman is where you write scripts to automatically check API responses after each request.
pm.test() defines individual named tests that run independently and report pass or fail clearly.
Assertions inside pm.test() throw errors on failure, which Postman catches to mark tests as failed.
You can write multiple, dynamic, and asynchronous tests using pm.test() to cover complex API scenarios.
Understanding pm.test() enables effective API validation and integration into automated testing workflows.

Practice

(1/5)
1. What is the main purpose of the pm.test() function in Postman's Tests tab?
easy
A. To define a named test and run assertions on the API response
B. To send an API request to the server
C. To format the API response data
D. To create a new collection in Postman

Solution

  1. Step 1: Understand the role of pm.test()

    The pm.test() function is used to define a test with a descriptive name and a function that contains checks or assertions.
  2. Step 2: Identify what pm.test() does in the Tests tab

    It runs the test function to verify if the API response meets expected conditions, helping automate validation.
  3. Final Answer:

    To define a named test and run assertions on the API response -> Option A
  4. Quick Check:

    pm.test() defines tests = A [OK]
Hint: pm.test() names and runs checks on responses [OK]
Common Mistakes:
  • Confusing pm.test() with sending requests
  • Thinking pm.test() formats data
  • Assuming pm.test() creates collections
2. Which of the following is the correct syntax to write a test in Postman that checks if the response status code is 200?
easy
A. pm.test('Status code is 200', function { pm.response.status == 200 });
B. pm.test('Status code is 200', () => pm.response.to.have.status(200));
C. pm.test('Status code is 200', pm.response.status === 200);
D. pm.test('Status code is 200', () => pm.response.status = 200);

Solution

  1. Step 1: Review correct pm.test() syntax

    The correct syntax uses a test name string and a function with assertions inside, like an arrow function.
  2. Step 2: Check assertion method for status code

    Using pm.response.to.have.status(200) is the proper way to assert status code 200.
  3. Final Answer:

    pm.test('Status code is 200', () => pm.response.to.have.status(200)); -> Option B
  4. Quick Check:

    Correct syntax uses arrow function and .to.have.status() [OK]
Hint: Use arrow function and .to.have.status() for status checks [OK]
Common Mistakes:
  • Passing boolean instead of function to pm.test()
  • Using assignment '=' instead of comparison '=='
  • Omitting parentheses in function declaration
3. Consider this test code in Postman:
pm.test('Response has userId 1', () => {
  const jsonData = pm.response.json();
  pm.expect(jsonData.userId).to.eql(1);
});

What will happen if the API response JSON is {"userId": 2}?
medium
A. The test will fail because userId is not 1
B. The test will pass because userId exists
C. The test will throw a syntax error
D. The test will be skipped automatically

Solution

  1. Step 1: Understand the test assertion

    The test checks if jsonData.userId equals 1 using pm.expect().to.eql(1).
  2. Step 2: Compare actual response value

    The response has userId as 2, which does not equal 1, so the assertion fails.
  3. Final Answer:

    The test will fail because userId is not 1 -> Option A
  4. Quick Check:

    Assertion fails if values differ = B [OK]
Hint: pm.expect() fails if actual ≠ expected [OK]
Common Mistakes:
  • Assuming test passes if key exists
  • Confusing eql() with assignment
  • Thinking test skips on mismatch
4. You wrote this test in Postman:
pm.test('Check response time', () => {
  pm.expect(pm.response.responseTime).to.be.below(200);
});

But the test always fails even when response time is below 200ms. What is the likely error?
medium
A. The property pm.response.responseTime is correct, but the test function is missing parentheses
B. Incorrect property name; should be pm.response.response_time
C. The property pm.response.responseTime is correct, but the test fails if responseTime is undefined or not a number
D. Using to.be.below instead of to.be.lessThan

Solution

  1. Step 1: Verify property name and assertion

    pm.response.responseTime is the correct property for response time in milliseconds, and to.be.below() is valid syntax.
  2. Step 2: Consider why test fails despite correct syntax

    If responseTime is undefined or not a number, the assertion will fail even if the actual response time is low.
  3. Final Answer:

    The property pm.response.responseTime is correct, but the test fails if responseTime is undefined or not a number -> Option C
  4. Quick Check:

    Undefined or wrong type causes assertion failure = A [OK]
Hint: Check property exists and is number before asserting [OK]
Common Mistakes:
  • Assuming wrong assertion method causes failure
  • Using incorrect property names
  • Missing parentheses in arrow function
5. You want to write a Postman test that checks if the response JSON contains a non-empty array called items and that each item has a price greater than 0. Which test code correctly implements this?
hard
A. pm.test('Items array and prices', () => { const jsonData = pm.response.json(); pm.expect(Array.isArray(jsonData.items)).to.be.true; pm.expect(jsonData.items.length).to.be.above(0); jsonData.items.forEach(item => pm.expect(item.price).to.be.above(0)); });
B. pm.test('Items array and prices', () => { const jsonData = pm.response.json(); pm.expect(jsonData.items).to.be.an('array').and.not.empty; pm.expect(jsonData.items.every(item => item.price > 0)).to.be.true; });
C. pm.test('Items array and prices', () => { const jsonData = pm.response.json(); pm.expect(jsonData.items).to.exist; pm.expect(jsonData.items.length > 0); jsonData.items.forEach(item => pm.expect(item.price > 0)); });
D. pm.test('Items array and prices', () => { const jsonData = pm.response.json(); pm.expect(jsonData.items).to.be.an('array'); pm.expect(jsonData.items.length).to.be.greaterThan(0); jsonData.items.forEach(item => pm.expect(item.price).to.be.greaterThan(0)); });

Solution

  1. Step 1: Check array existence and length

    pm.test('Items array and prices', () => { const jsonData = pm.response.json(); pm.expect(jsonData.items).to.be.an('array'); pm.expect(jsonData.items.length).to.be.greaterThan(0); jsonData.items.forEach(item => pm.expect(item.price).to.be.greaterThan(0)); }); correctly uses pm.expect(jsonData.items).to.be.an('array') and to.be.greaterThan(0) to verify the array is non-empty.
  2. Step 2: Verify each item's price check

    pm.test('Items array and prices', () => { const jsonData = pm.response.json(); pm.expect(jsonData.items).to.be.an('array'); pm.expect(jsonData.items.length).to.be.greaterThan(0); jsonData.items.forEach(item => pm.expect(item.price).to.be.greaterThan(0)); }); uses pm.expect(item.price).to.be.greaterThan(0) inside a forEach loop, which is valid and clear.
  3. Step 3: Compare with other options

    Options A and B use slightly different syntax but A uses to.be.above(0) which is valid but less common than to.be.greaterThan(0). B uses every() which is valid but chaining to.be.an('array').and.not.empty is not standard Chai syntax in Postman. C has incorrect assertions missing function calls.
  4. Final Answer:

    Option D correctly implements all checks with valid syntax -> Option D
  5. Quick Check:

    Use .to.be.an('array') and .to.be.greaterThan() for checks [OK]
Hint: Use .to.be.an('array') and .to.be.greaterThan() for clear checks [OK]
Common Mistakes:
  • Using incorrect assertion chaining syntax
  • Missing function calls in pm.expect()
  • Not checking array length before iterating