0
0
Postmantesting~15 mins

Condition block in Postman - Build an Automation Script

Choose your learning style9 modes available
Validate response status and content using condition block in Postman test script
Preconditions (2)
Step 1: Send a GET request to https://jsonplaceholder.typicode.com/posts/1
Step 2: In the Tests tab, write a condition block to check if the response status code is 200
Step 3: If status code is 200, assert that the response body contains a userId field with value 1
Step 4: If status code is not 200, assert that the response body contains an error message
✅ Expected Result: Test passes if status code is 200 and userId is 1; otherwise, test fails with appropriate error assertion
Automation Requirements - Postman test scripts (JavaScript)
Assertions Needed:
Assert response status code equals 200
Assert response body contains userId with value 1 when status is 200
Assert response body contains error message when status is not 200
Best Practices:
Use pm.response.to.have.status for status code assertion
Use pm.expect for assertions
Use if-else condition blocks to handle different response scenarios
Keep test scripts readable and maintainable
Automated Solution
Postman
pm.test('Condition block test for status and response body', function () {
    if (pm.response.code === 200) {
        pm.expect(pm.response.json()).to.have.property('userId', 1);
    } else {
        pm.expect(pm.response.text()).to.include('error');
    }
});

This test script uses a condition block to check the response status code.

If the status code is 200, it asserts that the JSON response has a property userId equal to 1.

If the status code is not 200, it asserts that the response text includes the word error.

This approach ensures the test adapts to different response scenarios and verifies the expected content accordingly.

Common Mistakes - 3 Pitfalls
Not checking the response status code before asserting response body
Using pm.response.json() without verifying response is JSON
Hardcoding assertions without condition blocks
Bonus Challenge

Now add data-driven testing with 3 different API endpoints and validate their status and response content using condition blocks

Show Hint