Clean Up Your Test Names in Postman

testing postman

Postman tests are a great way to cover integration testing for your API's, especially when you can have them run nightly from a DevOps pipeline. However, when running those tests in Newman, Postman's CLI tool, tests named things like "Return status 200" don't necessarily give you a good clue as to which endpoint was running.

I wanted to simplify the naming of a large suite of Postman tests as much as possible and the following is the approach I took.

It is possible, as well as running tests from the request level, to run tests from the collection level, so that they run for all tests. Here's my collection-level test script:

const method = pm.request.url.path.join("/").replace(/^api\//, "");
pm.environment.set("currentMethod", method);

pm.test(`${method} - Status code is 200`, () => {
  pm.response.to.have.status(200);
});

pm.test(`${method} - Response time below 500ms`, () => {
  pm.expect(pm.response.responseTime).to.be.below(500);
});

The first line is building the first part of the test title for me - the endpoint that is being tested. For example, if the endpoint is:

https://someapi.domain.com/api/contacts/v1/getcontact?id=1

Then the "method" constant will be:

contacts/v1/getcontact

I'm using a regex to remove the api prefix from my test name.

The next line then injects that into the current environment variables. We'll need it later.

Then there's a couple of tests that I want to run for every endpoint in the collection, the HTTP status code and response time. They use string interpolation to inject the current endpoint in before the rest of the test title.

All that's left to do now is retrieve that method title within each individual endpoint tests to use it in the same way:

var method = pm.environment.get("currentMethod");

var contact = pm.response.json();

pm.test(`${method} - Name valid`, () => {
    pm.expect(contact).to.have.property("name");
});

pm.test(`${method} - ID valid`, () => {
    pm.expect(contact.id).to.be.greaterThan(0);
});

And there you have it. Add a similar set of tests for a different endpoint, run this suite and you'd see:

PASS contacts/v1/getcontact - Status code is 200
PASS contacts/v1/getcontact - Response time below 500ms
PASS contacts/v1/getcontact - Name valid
PASS contacts/v1/getcontact - ID valid
PASS contacts/v1/getaddress - Status code is 200
PASS contacts/v1/getaddress - Response time below 500ms
PASS contacts/v1/getaddress - Name valid
PASS contacts/v1/getaddress - ID valid

Create multiple folders under the collection for each endpoint, and they'll all be correctly labelled within the test results, no matter what the endpoint is.

Happy testing!