Bird
Raised Fist0
Postmantesting~15 mins

JSON value assertions 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 - JSON value assertions
What is it?
JSON value assertions are checks you write to confirm that the data returned by an API matches what you expect. They look inside the JSON response and compare specific values or structures to your test rules. This helps ensure the API works correctly and returns the right information every time.
Why it matters
Without JSON value assertions, you might not notice when an API returns wrong or broken data. This can cause apps to fail or behave unpredictably, leading to bad user experiences or costly bugs. Assertions catch these problems early, saving time and improving software quality.
Where it fits
Before learning JSON value assertions, you should understand basic API requests and JSON format. After mastering assertions, you can explore automated test suites, data-driven testing, and continuous integration to build reliable API tests.
Mental Model
Core Idea
JSON value assertions are like asking a question about a returned data package and expecting a specific answer to confirm correctness.
Think of it like...
Imagine receiving a letter with a list of items you ordered. You check if the letter says the right items and quantities. JSON value assertions do the same for API responses, verifying the 'letter' matches your order.
┌─────────────────────────────┐
│       API Response JSON      │
│ ┌─────────────┐             │
│ │ {           │             │
│ │  "name": "John",       │
│ │  "age": 30,              │
│ │  "active": true          │
│ │ }           │             │
│ └─────────────┘             │
│           │                 │
│           ▼                 │
│ ┌─────────────────────────┐ │
│ │ JSON Value Assertions   │ │
│ │ - Check name == "John" │ │
│ │ - Check age == 30        │ │
│ │ - Check active == true   │ │
│ └─────────────────────────┘ │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding JSON Structure Basics
🤔
Concept: Learn what JSON is and how data is organized inside it.
JSON (JavaScript Object Notation) is a way to store data as key-value pairs. For example: {"name": "Alice", "age": 25} means the name is Alice and age is 25. JSON can have nested objects and arrays too.
Result
You can read and understand simple JSON data returned by APIs.
Understanding JSON structure is essential because assertions target specific keys and values inside this format.
2
FoundationBasics of API Response Testing
🤔
Concept: Learn how to send a request and get a JSON response to test.
Using Postman, you send an API request and receive a JSON response. This response contains data you want to check. For example, a GET request to /users/1 might return {"id":1,"name":"Bob"}.
Result
You can fetch JSON data from an API to prepare for assertions.
Knowing how to get JSON responses is the first step before you can check their values.
3
IntermediateWriting Simple JSON Value Assertions
🤔Before reading on: do you think you can check if a JSON key exists or equals a value? Commit to your answer.
Concept: Learn how to write assertions that check if a JSON key exists and matches an expected value.
In Postman tests tab, you write code like: pm.test('Name is Alice', () => { pm.expect(pm.response.json().name).to.eql('Alice'); }); This checks if the 'name' key equals 'Alice'.
Result
Tests pass if the value matches; fail if it doesn't.
Knowing how to write simple assertions lets you verify API correctness at a basic level.
4
IntermediateUsing Deep Property Assertions
🤔Before reading on: do you think you can check values inside nested JSON objects or arrays? Commit to your answer.
Concept: Learn to assert values inside nested JSON structures using dot notation or array indexes.
For nested JSON like {"user": {"id": 1, "roles": ["admin", "user"]}}, you can check pm.expect(pm.response.json().user.roles[0]).to.eql('admin'); to verify the first role.
Result
You can validate complex JSON responses with nested data.
Mastering deep property assertions allows testing real-world APIs with complex data.
5
IntermediateCombining Multiple Assertions in One Test
🤔Before reading on: do you think you can check several JSON values in a single test block? Commit to your answer.
Concept: Learn to write multiple assertions inside one test to check several JSON values at once.
Inside pm.test, you can write multiple pm.expect statements: pm.test('Check user data', () => { const json = pm.response.json(); pm.expect(json.name).to.eql('Alice'); pm.expect(json.age).to.eql(25); pm.expect(json.active).to.be.true; });
Result
You get a single test that verifies many parts of the response.
Grouping assertions improves test clarity and efficiency.
6
AdvancedHandling Dynamic JSON Values in Assertions
🤔Before reading on: do you think you can assert values that change every time, like timestamps? Commit to your answer.
Concept: Learn strategies to assert JSON values that are dynamic or unpredictable, like dates or IDs.
Instead of exact matches, use conditions: pm.expect(json.timestamp).to.be.a('string'); or pm.expect(json.id).to.be.a('number'); You can also use regex or check value ranges.
Result
Tests pass even when some JSON values vary, focusing on type or pattern.
Handling dynamic values prevents false test failures and makes tests robust.
7
ExpertCustom Assertion Functions for Reusable Checks
🤔Before reading on: do you think writing your own assertion helpers can simplify complex JSON tests? Commit to your answer.
Concept: Learn to create reusable functions to assert common JSON patterns or structures across tests.
Define functions like function assertUser(json) { pm.expect(json).to.have.property('id'); pm.expect(json.name).to.be.a('string'); } Then call assertUser(pm.response.json()) in multiple tests.
Result
You write less code and keep tests consistent and maintainable.
Custom assertion functions scale testing efforts and reduce errors in large projects.
Under the Hood
Postman runs test scripts after receiving an API response. The response body is parsed from JSON text into a JavaScript object. Assertions use the Chai assertion library to compare expected values with actual JSON data. If an assertion fails, Postman marks the test as failed and reports the error.
Why designed this way?
Postman uses JavaScript and Chai because they are flexible and widely known, allowing testers to write expressive and powerful tests. Parsing JSON into objects lets testers access data easily with dot notation. This design balances ease of use with powerful testing capabilities.
┌───────────────┐
│ API Response  │
│ (JSON text)   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ JSON Parsing  │
│ (to JS object)│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Test Script   │
│ (JS + Chai)   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Assertion     │
│ Evaluation    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Test Result   │
│ (Pass/Fail)   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think asserting a JSON key exists means its value is correct? Commit to yes or no.
Common Belief:If a JSON key exists in the response, the value must be correct.
Tap to reveal reality
Reality:A key can exist but have a wrong or unexpected value. Assertions must check both presence and correctness.
Why it matters:Relying only on key existence can miss bugs where the API returns wrong data, causing silent failures.
Quick: Do you think you can assert JSON values by comparing the whole response text? Commit to yes or no.
Common Belief:Comparing the entire JSON response as text is enough for testing correctness.
Tap to reveal reality
Reality:Exact text comparison is fragile because order of keys or formatting can change without affecting data meaning. Value assertions target specific data points more reliably.
Why it matters:Using whole-text comparison leads to flaky tests that fail unnecessarily, wasting time.
Quick: Do you think you must always check every JSON key in a response? Commit to yes or no.
Common Belief:You should assert every key in the JSON response to be thorough.
Tap to reveal reality
Reality:Testing every key is often unnecessary and inefficient. Focus on keys critical to your app's logic or contract.
Why it matters:Over-testing wastes effort and makes tests brittle to harmless changes.
Quick: Do you think JSON value assertions can only check exact values? Commit to yes or no.
Common Belief:Assertions only work if you know the exact value to expect.
Tap to reveal reality
Reality:Assertions can check types, patterns, ranges, or conditions, not just exact matches.
Why it matters:Knowing this allows testing APIs with dynamic or partial data effectively.
Expert Zone
1
Some JSON keys may be optional or nullable; assertions must handle these cases gracefully to avoid false failures.
2
Using schema validation libraries alongside value assertions can improve test coverage and catch structural errors.
3
Chaining assertions and using asynchronous tests in Postman can handle complex workflows and dependent API calls.
When NOT to use
JSON value assertions are less effective when testing non-JSON responses like HTML or binary data. In those cases, use other assertion methods like status code checks or content-type validations.
Production Patterns
In real projects, teams write reusable assertion libraries, integrate Postman tests into CI pipelines, and combine JSON value assertions with performance and security tests for comprehensive API quality assurance.
Connections
Schema Validation
Builds-on
Understanding JSON value assertions helps grasp schema validation, which checks entire JSON structures against formal rules, improving test completeness.
Unit Testing
Same pattern
JSON value assertions follow the same principle as unit tests: checking expected outputs for given inputs, reinforcing the core testing mindset.
Quality Control in Manufacturing
Analogous process
Just like inspecting products on a factory line for defects, JSON value assertions inspect API responses to catch errors early, showing how testing concepts cross domains.
Common Pitfalls
#1Checking JSON keys without verifying their values.
Wrong approach:pm.test('Check key exists', () => { pm.expect(pm.response.json()).to.have.property('name'); });
Correct approach:pm.test('Check key and value', () => { pm.expect(pm.response.json().name).to.eql('Alice'); });
Root cause:Assuming presence of a key guarantees correct data, ignoring value correctness.
#2Using exact string match on entire JSON response.
Wrong approach:pm.test('Exact response match', () => { pm.expect(pm.response.text()).to.eql('{"name":"Alice","age":25}'); });
Correct approach:pm.test('Value assertions', () => { const json = pm.response.json(); pm.expect(json.name).to.eql('Alice'); pm.expect(json.age).to.eql(25); });
Root cause:Not understanding JSON parsing and the fragility of exact text comparisons.
#3Failing tests due to dynamic values like timestamps.
Wrong approach:pm.test('Timestamp exact match', () => { pm.expect(pm.response.json().timestamp).to.eql('2024-06-01T12:00:00Z'); });
Correct approach:pm.test('Timestamp type check', () => { pm.expect(pm.response.json().timestamp).to.be.a('string'); });
Root cause:Trying to assert exact values for data that changes every response.
Key Takeaways
JSON value assertions let you check specific data inside API responses to ensure correctness.
They work by parsing JSON into objects and comparing expected values using code in Postman tests.
Effective assertions focus on important keys and handle dynamic data with flexible checks.
Writing reusable assertion functions improves test maintainability and scalability.
Understanding JSON value assertions is key to building reliable automated API tests.

Practice

(1/5)
1. What is the main purpose of JSON value assertions in Postman?
easy
A. To send requests to the server
B. To check if the API response data matches expected values
C. To format JSON data for display
D. To create new API endpoints

Solution

  1. Step 1: Understand JSON value assertions

    JSON value assertions verify that the data returned by an API is correct and matches what is expected.
  2. Step 2: Identify the purpose in Postman

    In Postman, assertions are used to check API responses, not to send requests or format data.
  3. Final Answer:

    To check if the API response data matches expected values -> Option B
  4. Quick Check:

    Assertions verify response data = A [OK]
Hint: Assertions check response data correctness fast [OK]
Common Mistakes:
  • Confusing assertions with sending requests
  • Thinking assertions format JSON
  • Believing assertions create APIs
2. Which of the following is the correct syntax to assert that the JSON response has a key 'status' with value 'success' in Postman?
easy
A. pm.expect(response.status).to.equal('success');
B. pm.response.json().status == 'success';
C. pm.expect(pm.response.json().status).to.eql('success');
D. assert(pm.response.status == 'success');

Solution

  1. Step 1: Identify correct assertion syntax in Postman

    Postman uses pm.expect() with the JSON response accessed by pm.response.json(). The method to check equality is .to.eql()
  2. Step 2: Eliminate incorrect options

    pm.expect(pm.response.json().status).to.eql('success'); correctly uses pm.expect(pm.response.json().status).to.eql('success'); The other options have syntax errors or incorrect usage such as wrong response reference, missing pm.expect, or invalid functions.
  3. Final Answer:

    pm.expect(pm.response.json().status).to.eql('success'); -> Option C
  4. Quick Check:

    pm.expect + pm.response.json() + .to.eql() = D [OK]
Hint: Use pm.expect with pm.response.json() and .to.eql() [OK]
Common Mistakes:
  • Using == instead of .to.eql()
  • Missing pm.expect wrapper
  • Referencing response incorrectly
3. Given the following Postman test code:
const jsonData = pm.response.json();
pm.expect(jsonData.user.id).to.eql(12345);

What will happen if the API response JSON is { "user": { "id": 12345, "name": "Alice" } }?
medium
A. The test will pass because the user id matches 12345
B. The test will fail because the user id is a number, not a string
C. The test will fail due to syntax error
D. The test will pass but ignore the user id

Solution

  1. Step 1: Analyze the JSON response

    The response JSON has user.id equal to the number 12345, which matches the expected value in the assertion.
  2. Step 2: Understand the assertion behavior

    pm.expect().to.eql() compares values strictly but 12345 number matches 12345 number, so the assertion passes.
  3. Final Answer:

    The test will pass because the user id matches 12345 -> Option A
  4. Quick Check:

    Matching values = test passes = B [OK]
Hint: Check exact value and type in JSON for assertion [OK]
Common Mistakes:
  • Assuming number vs string mismatch causes failure
  • Confusing syntax error with assertion failure
  • Ignoring actual JSON structure
4. You wrote this Postman test:
pm.expect(pm.response.json().data).to.equal({"status": "active"});

But the test always fails even when the API returns { "data": { "status": "active" } }. What is the likely problem?
medium
A. The assertion should use .to.eql() for deep equality
B. The response JSON is not parsed correctly
C. Using .to.equal() instead of .to.eql() for object comparison
D. The test is missing pm.response.json() call

Solution

  1. Step 1: Understand difference between .to.equal() and .to.eql()

    .to.equal() checks strict equality for primitives but can fail for objects or deep checks. .to.eql() is used for deep equality including strings and objects.
  2. Step 2: Identify the correct assertion for object value

    Since 'data' is an object, .to.eql() is required for deep equality checks. Using .to.equal() performs strict reference equality (===), which fails for distinct object instances even if contents match.
  3. Final Answer:

    The assertion should use .to.eql() for deep equality -> Option A
  4. Quick Check:

    Use .to.eql() for object equality in JSON assertions [OK]
Hint: Use .to.eql() for JSON value assertions, not .to.equal() [OK]
Common Mistakes:
  • Confusing .to.equal() and .to.eql()
  • Assuming JSON parsing failed
  • Missing pm.response.json() call
5. You want to assert that the API response JSON contains an array 'items' where each item has a 'price' greater than 0. Which Postman test code correctly checks this?
hard
A. pm.expect(pm.response.json().items.filter(price > 0)).to.not.be.empty;
B. pm.expect(pm.response.json().items).to.have.property('price').above(0);
C. pm.expect(pm.response.json().items.price).to.be.above(0);
D. pm.expect(pm.response.json().items.every(item => item.price > 0)).to.be.true;

Solution

  1. Step 1: Understand the requirement

    We need to check that every item in the 'items' array has a 'price' greater than 0.
  2. Step 2: Analyze each option

    pm.expect(pm.response.json().items.every(item => item.price > 0)).to.be.true; uses JavaScript's every() method to check all items satisfy price > 0, then asserts true. This is correct.
    pm.expect(pm.response.json().items).to.have.property('price').above(0); incorrectly tries to check property on array directly.
    pm.expect(pm.response.json().items.price).to.be.above(0); tries to access items.price which is invalid since items is an array.
    pm.expect(pm.response.json().items.filter(price > 0)).to.not.be.empty; uses filter incorrectly without a function.
  3. Final Answer:

    pm.expect(pm.response.json().items.every(item => item.price > 0)).to.be.true; -> Option D
  4. Quick Check:

    Use every() with pm.expect to check all array items [OK]
Hint: Use .every() to assert all array items meet condition [OK]
Common Mistakes:
  • Trying to access property on array directly
  • Using filter without a function
  • Misusing assertion methods on arrays