Default and conditional responses in Postman - Build an Automation Script
/* Test script for default response (no query parameter) */ pm.test('Status code is 200', () => { pm.response.to.have.status(200); }); pm.test('Response has default JSON message', () => { const jsonData = pm.response.json(); pm.expect(jsonData).to.have.property('message'); pm.expect(jsonData.message).to.eql('Default response'); }); /* Test script for type=json */ // Run this script after sending request with ?type=json pm.test('Status code is 200', () => { pm.response.to.have.status(200); }); pm.test('Response is valid JSON with expected structure', () => { const jsonData = pm.response.json(); pm.expect(jsonData).to.have.property('data'); pm.expect(jsonData.data).to.be.an('array'); }); /* Test script for type=xml */ // Run this script after sending request with ?type=xml const xml2Json = require('xml2json'); pm.test('Status code is 200', () => { pm.response.to.have.status(200); }); pm.test('Response is valid XML with expected root element', () => { const xmlData = pm.response.text(); let jsonObj; try { jsonObj = JSON.parse(xml2Json.toJson(xmlData)); } catch (e) { pm.expect.fail('Response is not valid XML'); } pm.expect(jsonObj).to.have.property('response'); });
This Postman test script is divided into three parts for each request variation.
First, it checks the default response when no query parameter is sent. It asserts the status code is 200 and the JSON response contains a 'message' property with value 'Default response'.
Second, for the request with ?type=json, it asserts the status code and verifies the response JSON has a 'data' property which is an array, indicating the expected JSON structure.
Third, for the request with ?type=xml, it asserts the status code and uses the xml2json library to convert XML response text to JSON. It then checks that the converted JSON has a 'response' root element, confirming valid XML structure.
Each test uses Postman's pm API for assertions and parsing. This approach keeps tests clear, focused, and maintainable.
Now add data-driven testing with 3 different 'type' parameter values: none, 'json', and 'xml' in a single Postman collection test.