0
0
Postmantesting~15 mins

Dynamic assertion values in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify dynamic values in API response
Preconditions (3)
Step 1: Set the GET request URL to https://api.example.com/user/12345
Step 2: Send the GET request
Step 3: Capture the 'createdAt' field from the response
Step 4: Verify that the 'userId' field equals '12345'
Step 5: Verify that the 'createdAt' field is a valid ISO 8601 date string
Step 6: Verify that the 'status' field equals 'active'
✅ Expected Result: The response contains userId '12345', status 'active', and a valid ISO 8601 date string in 'createdAt'
Automation Requirements - Postman Tests (JavaScript)
Assertions Needed:
userId equals '12345'
status equals 'active'
'createdAt' is a valid ISO 8601 date string
Best Practices:
Use pm.response.json() to parse JSON response
Use dynamic assertions for date validation
Avoid hardcoding dynamic values except userId and status
Use descriptive assertion messages
Automated Solution
Postman
pm.test('Response has userId 12345', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData.userId).to.eql('12345');
});

pm.test('Response has status active', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData.status).to.eql('active');
});

pm.test('createdAt is a valid ISO 8601 date string', () => {
    const jsonData = pm.response.json();
    const createdAt = jsonData.createdAt;
    // Simple ISO 8601 regex check
    const iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.\d+)?Z$/;
    pm.expect(createdAt).to.match(iso8601Regex, 'createdAt should be ISO 8601 format');
    // Additional check: Date parse should not be NaN
    pm.expect(!isNaN(Date.parse(createdAt))).to.be.true;
});

This Postman test script uses pm.response.json() to parse the JSON response once per test for clarity.

First, it asserts that the userId field equals the expected static value '12345'.

Second, it asserts that the status field equals 'active'.

Third, it dynamically validates the createdAt field by checking it matches an ISO 8601 date format using a regular expression and also verifies that JavaScript can parse it as a valid date.

This approach ensures dynamic values like timestamps are validated properly without hardcoding exact values, making the test robust and reliable.

Common Mistakes - 3 Pitfalls
{'mistake': "Hardcoding the exact 'createdAt' timestamp value in assertion", 'why_bad': "The 'createdAt' value changes every time the API is called, so hardcoding causes test failures.", 'correct_approach': 'Use a dynamic check like regex or date parsing to validate the format instead of exact value.'}
Not parsing the response JSON before assertions
Using loose equality (==) instead of strict equality (=== or .eql) in assertions
Bonus Challenge

Now add data-driven testing with 3 different userIds: '12345', '67890', and 'abcde'. Verify userId and status for each.

Show Hint