0
0
Postmantesting~5 mins

Condition block in Postman

Choose your learning style9 modes available
Introduction

A condition block lets you run code only when certain things are true. It helps you check if your API response is correct or handle different cases.

Check if an API response status is 200 before testing the data.
Run different tests depending on the value of a response field.
Skip tests when a required field is missing in the response.
Log a message only if an error occurs in the response.
Syntax
Postman
if (condition) {
    // code to run if condition is true
} else {
    // code to run if condition is false
}

The condition is a statement that is either true or false.

The else part is optional and runs when the condition is false.

Examples
This runs a test only if the response status code is 200.
Postman
if (pm.response.code === 200) {
    pm.test('Status is 200', () => {
        pm.expect(pm.response.code).to.equal(200);
    });
}
This logs a message depending on the success field in the JSON response.
Postman
if (pm.response.json().success) {
    console.log('Success is true');
} else {
    console.log('Success is false');
}
Sample Program

This test checks if the user is active. It runs different assertions and logs messages based on the active field.

Postman
pm.test('Check user is active', () => {
    let jsonData = pm.response.json();
    if (jsonData.active) {
        pm.expect(jsonData.active).to.be.true;
        console.log('User is active');
    } else {
        pm.expect(jsonData.active).to.be.false;
        console.log('User is not active');
    }
});
OutputSuccess
Important Notes

Use strict equality === to avoid unexpected type conversions.

Always check if the response data exists before accessing fields to avoid errors.

Summary

Condition blocks let you run code only when certain things are true.

They help make tests smarter by handling different response cases.

Use if and optional else to control test flow.