Bird
Raised Fist0
Postmantesting~15 mins

Nested object assertions in Postman - Deep Dive

Choose your learning style10 modes available
Overview - Nested object assertions
What is it?
Nested object assertions are checks made on data structures that contain objects within objects, like a family tree or a folder inside a folder. In Postman, this means verifying values deep inside a JSON response, not just the top-level fields. This helps ensure that complex data returned by APIs is exactly as expected. It is essential for testing APIs that return detailed, layered information.
Why it matters
Without nested object assertions, testers might miss errors hidden deep inside the data, like a wrong phone number inside a user's contact info or a missing address in an order. This can cause bugs to slip into production, leading to broken features or bad user experiences. Nested assertions help catch these issues early, making software more reliable and trustworthy.
Where it fits
Before learning nested object assertions, you should understand basic API testing and simple assertions on flat JSON objects. After mastering nested assertions, you can move on to dynamic data validation, chaining requests, and automated test suites in Postman.
Mental Model
Core Idea
Nested object assertions let you check values inside layers of data, like opening boxes inside boxes to find exactly what you want.
Think of it like...
It's like checking a family photo album where each page has pictures of different family members, and you want to confirm the name and birthday of a specific cousin on page three.
Response JSON
┌─────────────┐
│ user        │
│ ┌─────────┐ │
│ │ address │ │
│ │ ┌─────┐ │ │
│ │ │city │ │ │
│ │ └─────┘ │ │
│ └─────────┘ │
└─────────────┘

Assertion path: user.address.city
Build-Up - 7 Steps
1
FoundationUnderstanding JSON structure basics
🤔
Concept: Learn what JSON objects and nested objects are and how they look.
JSON is a way to organize data using key-value pairs. An object is a set of keys and values inside curly braces {}. Nested objects are objects inside other objects. For example: { "user": { "name": "Alice", "address": { "city": "Wonderland" } } } Here, "address" is a nested object inside "user".
Result
You can identify nested objects by seeing curly braces inside other curly braces.
Understanding JSON structure is essential because nested assertions rely on navigating these layers correctly.
2
FoundationBasic assertions on flat JSON fields
🤔
Concept: Learn how to write simple assertions on top-level JSON keys in Postman.
In Postman tests, you can check a value like this: pm.test('Check user name', () => { const jsonData = pm.response.json(); pm.expect(jsonData.name).to.eql('Alice'); }); This checks that the 'name' key equals 'Alice'.
Result
Test passes if the 'name' is exactly 'Alice', fails otherwise.
Mastering simple assertions builds the foundation for more complex nested checks.
3
IntermediateAccessing nested objects in assertions
🤔Before reading on: do you think you can access nested values using dot notation like jsonData.user.address.city or do you need a special method? Commit to your answer.
Concept: Learn how to reach deep values inside nested objects using dot notation or bracket notation.
To check nested values, you use dot notation: pm.test('Check city name', () => { const jsonData = pm.response.json(); pm.expect(jsonData.user.address.city).to.eql('Wonderland'); }); You can also use bracket notation if keys have spaces or special characters: pm.expect(jsonData['user']['address']['city']).to.eql('Wonderland');
Result
Test passes if the city is 'Wonderland', fails if missing or different.
Knowing how to navigate nested objects lets you verify any detail inside complex API responses.
4
IntermediateUsing deep property assertions with chai
🤔Before reading on: do you think pm.expect(jsonData).to.have.property('user.address.city') works directly, or do you need a special way to check nested properties? Commit to your answer.
Concept: Learn how to use chai's 'deep.property' assertion to check nested keys in one statement.
Chai assertion library supports checking nested properties with 'deep.property': pm.test('Check nested property', () => { const jsonData = pm.response.json(); pm.expect(jsonData).to.have.deep.property('user.address.city', 'Wonderland'); }); This checks that the nested path exists and equals the value.
Result
Test passes if the nested property exists and matches the expected value.
Using deep.property simplifies nested assertions and makes tests cleaner and easier to read.
5
IntermediateHandling arrays inside nested objects
🤔Before reading on: do you think you can assert values inside arrays nested in objects using the same dot notation, or do you need loops or special methods? Commit to your answer.
Concept: Learn how to assert values inside arrays that are nested within objects.
If a nested object contains an array, you can access elements by index: { "user": { "phones": ["123-456", "789-012"] } } To check the first phone number: pm.test('Check first phone', () => { const jsonData = pm.response.json(); pm.expect(jsonData.user.phones[0]).to.eql('123-456'); }); For multiple checks, you can loop: jsonData.user.phones.forEach(phone => { pm.expect(phone).to.match(/^\d{3}-\d{3}$/); });
Result
Tests pass if phone numbers match expected values or patterns.
Understanding how to handle arrays inside nested objects is key for testing real-world API responses.
6
AdvancedDynamic nested assertions with variables
🤔Before reading on: do you think you can build assertion paths dynamically using variables, or must paths be hardcoded? Commit to your answer.
Concept: Learn how to create assertion paths dynamically to test varying nested data structures.
Sometimes the nested keys or indexes change. You can build paths dynamically: const section = 'address'; const field = 'city'; pm.test('Dynamic nested assertion', () => { const jsonData = pm.response.json(); pm.expect(jsonData.user[section][field]).to.eql('Wonderland'); }); This lets you reuse code for different nested paths.
Result
Test passes if the dynamically accessed nested value matches expected.
Dynamic paths make tests flexible and maintainable when dealing with changing API responses.
7
ExpertAvoiding pitfalls with missing nested keys
🤔Before reading on: do you think accessing a missing nested key like jsonData.user.address.city throws an error or returns undefined in Postman tests? Commit to your answer.
Concept: Learn how to safely assert nested values when some keys might be missing to avoid runtime errors.
If a nested key is missing, accessing deeper keys causes errors: // This throws if address is missing pm.expect(jsonData.user.address.city).to.eql('Wonderland'); Use optional chaining (supported in Postman): pm.expect(jsonData.user.address?.city).to.eql('Wonderland'); Or check existence first: pm.expect(jsonData.user).to.have.property('address'); if (jsonData.user.address) { pm.expect(jsonData.user.address.city).to.eql('Wonderland'); } This prevents tests from crashing.
Result
Tests run safely without errors even if some nested keys are missing.
Handling missing keys gracefully prevents false test failures and improves test robustness.
Under the Hood
Postman parses the API response JSON into a JavaScript object. Assertions access this object using JavaScript property accessors. Nested objects are represented as nested JavaScript objects. When you use dot notation or bracket notation, JavaScript looks up each key step-by-step. If a key is missing, accessing deeper keys throws an error unless optional chaining is used. Chai assertion library extends this by allowing deep property checks that traverse nested keys internally.
Why designed this way?
JavaScript's object model naturally represents JSON data, making it easy to access nested data with familiar syntax. Chai's deep.property was designed to simplify nested assertions without writing verbose code. Optional chaining was introduced to avoid runtime errors when accessing missing nested keys, improving developer experience and test stability.
API Response JSON
┌─────────────┐
│ {           │
│  user: {    │
│    name: "Alice",
│    address: {
│      city: "Wonderland"
│    }
│  }
│ }
└─────────────┘

Postman parses → JavaScript object

Access path:
jsonData → user → address → city

Chai deep.property checks nested keys internally

Optional chaining:
jsonData.user?.address?.city
Myth Busters - 4 Common Misconceptions
Quick: Do you think accessing a missing nested key returns undefined or throws an error? Commit to your answer.
Common Belief:Accessing any nested key that doesn't exist just returns undefined safely.
Tap to reveal reality
Reality:Accessing a missing nested key deeper than the first missing level throws a runtime error unless optional chaining is used.
Why it matters:Tests can crash unexpectedly, causing confusion and false negatives if missing keys are not handled properly.
Quick: Can you assert nested properties directly with pm.expect(jsonData).to.have.property('user.address.city')? Commit to your answer.
Common Belief:You can check nested properties directly with 'have.property' using dot notation string.
Tap to reveal reality
Reality:The standard 'have.property' only checks top-level keys; to check nested keys, you must use 'deep.property'.
Why it matters:Using the wrong assertion method leads to tests passing or failing incorrectly, hiding real issues.
Quick: Do you think arrays inside nested objects require special handling different from normal objects? Commit to your answer.
Common Belief:Arrays inside nested objects behave the same as objects and can be asserted without indexing.
Tap to reveal reality
Reality:Arrays require accessing elements by index; you cannot assert the whole array as a single object property.
Why it matters:Ignoring array indexing causes incorrect assertions and missed bugs in list data.
Quick: Is it always better to write one big assertion for a nested object or multiple small assertions? Commit to your answer.
Common Belief:One big assertion checking the whole nested object is simpler and better.
Tap to reveal reality
Reality:Multiple small assertions give clearer test failures and easier debugging than one big assertion.
Why it matters:Big assertions can hide which exact nested value failed, slowing down bug fixing.
Expert Zone
1
Deep.property assertions internally parse the path string and traverse the object step-by-step, which can impact performance on very large responses.
2
Optional chaining is a recent JavaScript feature; older Postman versions may not support it, requiring manual existence checks.
3
When asserting arrays inside nested objects, using array methods like .some() or .every() combined with assertions can express complex conditions elegantly.
When NOT to use
Nested object assertions are not suitable when the API response is extremely large or deeply recursive, as tests may become slow or complex. In such cases, consider validating only critical fields or using schema validation tools like JSON Schema validators instead.
Production Patterns
In real-world API testing, nested assertions are combined with environment variables and data-driven tests to validate multiple scenarios. Teams often write reusable functions to assert common nested structures and use test reports to pinpoint exactly which nested field failed.
Connections
JSON Schema Validation
builds-on
Understanding nested object assertions helps grasp JSON Schema validation, which formally defines nested data shapes and automates deep checks.
Error Handling in Programming
similar pattern
Handling missing nested keys safely in assertions parallels error handling in programming, teaching defensive coding to avoid crashes.
Nested Folder Structures in File Systems
analogous structure
Navigating nested objects in JSON is like navigating folders inside folders on your computer, helping conceptualize deep data access.
Common Pitfalls
#1Accessing nested keys without checking if parent keys exist causes runtime errors.
Wrong approach:pm.expect(jsonData.user.address.city).to.eql('Wonderland'); // fails if address missing
Correct approach:pm.expect(jsonData.user.address?.city).to.eql('Wonderland'); // safe with optional chaining
Root cause:Assuming all nested keys always exist without defensive checks.
#2Using 'have.property' instead of 'have.deep.property' for nested keys leads to false test results.
Wrong approach:pm.expect(jsonData).to.have.property('user.address.city', 'Wonderland');
Correct approach:pm.expect(jsonData).to.have.deep.property('user.address.city', 'Wonderland');
Root cause:Misunderstanding how chai assertions handle nested properties.
#3Trying to assert an entire nested array as a single property without indexing or iteration.
Wrong approach:pm.expect(jsonData.user.phones).to.eql('123-456');
Correct approach:pm.expect(jsonData.user.phones[0]).to.eql('123-456');
Root cause:Confusing arrays with single values in nested data.
Key Takeaways
Nested object assertions let you verify deeply layered data inside API responses, ensuring thorough testing.
Using dot notation, bracket notation, and chai's deep.property makes accessing nested values straightforward and readable.
Handling missing nested keys safely with optional chaining or existence checks prevents test crashes and false failures.
Arrays inside nested objects require indexing or iteration to assert individual elements correctly.
Writing multiple small assertions on nested data improves test clarity and debugging over one large assertion.

Practice

(1/5)
1. In Postman, how do you access a nested property user.name in a JSON response for assertion?
easy
A. Use pm.expect(jsonData.user[name]) to access nested property.
B. Use pm.expect(jsonData.user.name) to assert the nested value.
C. Use pm.expect(jsonData['user-name']) to access nested property.
D. Use pm.expect(jsonData.user-name) to access nested property.

Solution

  1. Step 1: Understand JSON nested property access

    In JavaScript, nested properties are accessed using dot notation like object.property.
  2. Step 2: Apply correct syntax in Postman test

    To assert user.name, use pm.expect(jsonData.user.name) which correctly accesses the nested value.
  3. Final Answer:

    Use pm.expect(jsonData.user.name) to assert the nested value. -> Option B
  4. Quick Check:

    Dot notation = pm.expect(jsonData.user.name) [OK]
Hint: Use dot notation for nested JSON properties in assertions [OK]
Common Mistakes:
  • Using brackets incorrectly for nested keys
  • Using hyphens instead of dots for nested access
  • Missing quotes around string keys in bracket notation
2. Which of the following is the correct syntax to assert that response.body.data.user.age equals 30 in Postman?
easy
A. pm.test('Age is 30', () => { pm.expect(response.body.data.user.age).to.eql(30); });
B. pm.test('Age is 30', () => { pm.expect(response.body.data.user.age).to.equal('30'); });
C. pm.test('Age is 30', () => { pm.expect(response.body.data.user.age).to.be('30'); });
D. pm.test('Age is 30', () => { pm.expect(response.body.data.user.age).equals(30); });

Solution

  1. Step 1: Identify correct assertion method

    Postman uses Chai assertion library where to.eql(value) checks deep equality including numbers.
  2. Step 2: Check syntax correctness

    pm.test('Age is 30', () => { pm.expect(response.body.data.user.age).to.eql(30); }); uses to.eql(30) with correct arrow function and property access, matching expected number type.
  3. Final Answer:

    pm.test('Age is 30', () => { pm.expect(response.body.data.user.age).to.eql(30); }); -> Option A
  4. Quick Check:

    Use to.eql for value equality in Postman tests [OK]
Hint: Use to.eql() for exact value matching in Postman assertions [OK]
Common Mistakes:
  • Using string '30' instead of number 30
  • Using incorrect assertion methods like to.be()
  • Missing arrow function syntax in pm.test
3. Given the JSON response:
{"order": {"id": 101, "items": [{"name": "Pen", "qty": 3}, {"name": "Book", "qty": 2}]}}

What will this Postman test output?
pm.test('Check first item qty', () => {
  const jsonData = pm.response.json();
  pm.expect(jsonData.order.items[0].qty).to.eql(3);
});
medium
A. Test will pass because first item's qty is 3.
B. Test will fail because qty is 2 for first item.
C. Test will throw an error due to wrong index access.
D. Test will fail because items is not an array.

Solution

  1. Step 1: Analyze JSON structure and access

    The JSON has an array items with first element having qty: 3.
  2. Step 2: Check assertion correctness

    The test accesses items[0].qty and asserts it equals 3, which matches the JSON data.
  3. Final Answer:

    Test will pass because first item's qty is 3. -> Option A
  4. Quick Check:

    Array index 0 qty = 3 matches assertion [OK]
Hint: Check array index and property value carefully in nested assertions [OK]
Common Mistakes:
  • Confusing array index starting at 1 instead of 0
  • Assuming items is an object, not an array
  • Misreading qty values in nested objects
4. You wrote this Postman test:
pm.test('Check user city', () => {
  const jsonData = pm.response.json();
  pm.expect(jsonData.user.address.city).to.eql('New York');
});

But the test fails with error: TypeError: Cannot read property 'city' of undefined. What is the likely cause?
medium
A. The assertion method to.eql is incorrect for strings.
B. The city value is misspelled in the assertion.
C. The JSON response is not parsed correctly with pm.response.json().
D. The address property is missing or undefined in user.

Solution

  1. Step 1: Understand the error message

    The error says Cannot read property 'city' of undefined, meaning address is undefined.
  2. Step 2: Identify cause in nested access

    If jsonData.user.address is missing, trying to access .city causes this error.
  3. Final Answer:

    The address property is missing or undefined in user. -> Option D
  4. Quick Check:

    Undefined parent property causes TypeError in nested access [OK]
Hint: Check if all parent nested objects exist before accessing child [OK]
Common Mistakes:
  • Assuming all nested keys always exist
  • Ignoring error message details
  • Blaming assertion method instead of data structure
5. You receive this JSON response:
{"users": [{"id": 1, "profile": {"name": "Alice", "active": true}}, {"id": 2, "profile": {"name": "Bob", "active": false}}]}

Write a Postman test to assert that all users have a profile.active property set to true. Which code snippet correctly performs this nested object assertion?
hard
A. pm.test('All users active', () => { const users = pm.response.json().users; pm.expect(users[0].every(user => user.profile.active)).to.eql(true); });
B. pm.test('All users active', () => { const users = pm.response.json().users; pm.expect(users.profile.active).to.eql(true); });
C. pm.test('All users active', () => { const users = pm.response.json().users; users.forEach(user => { pm.expect(user.profile.active).to.eql(true); }); });
D. pm.test('All users active', () => { const users = pm.response.json().users; users.map(user => pm.expect(user.profile).to.eql(true)); });

Solution

  1. Step 1: Understand requirement to check all users' active status

    We must assert each user's profile.active is true.
  2. Step 2: Evaluate each option's approach

    pm.test('All users active', () => { const users = pm.response.json().users; users.forEach(user => { pm.expect(user.profile.active).to.eql(true); }); }); loops over users and asserts each profile.active equals true, which is correct and clear.
    pm.test('All users active', () => { const users = pm.response.json().users; pm.expect(users.profile.active).to.eql(true); }); wrongly tries to access users.profile.active which is invalid.
    pm.test('All users active', () => { const users = pm.response.json().users; pm.expect(users[0].every(user => user.profile.active)).to.eql(true); }); wrongly calls every() on users[0] (an object), causing TypeError as objects have no every method.
    pm.test('All users active', () => { const users = pm.response.json().users; users.map(user => pm.expect(user.profile).to.eql(true)); }); asserts user.profile equals true, but profile is an object not equal to true and misses .active.
  3. Final Answer:

    Use forEach loop to assert each user's profile.active is true. -> Option C
  4. Quick Check:

    Loop and assert each nested property for all items [OK]
Hint: Use forEach to assert nested properties on all array items [OK]
Common Mistakes:
  • Accessing nested property on array directly
  • Calling array methods like every() on single objects
  • Asserting entire object equals true instead of its boolean property
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard