Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexandreelise/5dc5036aa2172f3edc2b3860ddf24a2b to your computer and use it in GitHub Desktop.
Save alexandreelise/5dc5036aa2172f3edc2b3860ddf24a2b to your computer and use it in GitHub Desktop.
An example of heavily automated, optimized, effective Postman Collection level post-response script
let currentLocation = pm.collectionVariables.get('computed_current_location');
pm.test(`Successful 2xx request for ${currentLocation}`, () => {
pm.expect(pm.response.code).to.be.oneOf([200, 201, 202, 203, 204, 205, 206, 207, 208, 226]);
});
let method = pm.request.method;
if (['POST', 'PATCH', 'PUT'].includes(method)) {
pm.test("Content-Type is present for ${currentLocation}", () => {
pm.response.to.have.header("Content-Type");
});
}
if (['GET', 'POST', 'PATCH', 'PUT'].includes(method)) {
pm.test(`Check response format for ${currentLocation}`, () => {
const jsonData = pm.response.json();
pm.expect(pm.response.headers.get('Content-Type')).to.include('application/vnd.api+json');
pm.expect(jsonData).to.be.an('object');
});
}
if (method === 'POST') {
let jsonData = pm.response.json();
let resourceName = currentLocation;
let computedIdName = `last_created_${resourceName}_id`;
pm.test(`Save last created id for future requests for ${currentLocation}`, () => {
let last_created_id = jsonData?.data?.id || jsonData?.data[Math.max(0,jsonData.length - 1)]?.id;
if (last_created_id == null) {
pm.expect.fail(`Because ${computedIdName} is empty`);
}
pm.collectionVariables.set(`${computedIdName}`, last_created_id);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment