Sasgorilla
Sasgorilla

Reputation: 3130

How can I reuse a parameterized Postman test across endpoints?

In Postman, I can create a set of common tests that run after every endpoint in the collection/folder Tests tab, like so:

pm.test("status code is 200", function () {
    pm.response.to.have.status(200);
});

But how should I do this for my schema validation on the response object? Each endpoint has a different expected schema. So I have something like this on each individual endpoint:

const schema = { type: 'array', items: ... }

pm.test('response has correct schema', function () {
    const {data} = pm.response.json();
    pm.expect(tv4.validate(data, schema)).to.be.true;
});

I can't extract this up to the collection level because each schema is different.

Now I find that I want to tweak that test a little bit, but I'll have to copy-and-paste it into 50 endpoints.

What's the recommended pattern here for sharing a test across endpoints?

Upvotes: 0

Views: 419

Answers (1)

Mua Knight
Mua Knight

Reputation: 81

I had the same issue some years ago, and I found two ways to solve this:

  1. Create a folder for each structure object

You can group all your test cases that share the same structure into a new folder and create a test case for this group. The issue with this is that you will be repeating the requests in other folders. (For this solution, you will need to put your "tests cases" into the folder level)

  1. Create a validation using regular expressions (recommended)

Specify in the name of each request a set of rules (these rules will indicate what kind of structure or call they might have). Then you create a validation in the first parent folder for each type of variation (using regex). (You will need to create documentation and some if statements in your parent folder)

E.g.: [POST] CRLTHM Create a group of homes

Where each initial is meaning to:

  • CR: Response must be 201
  • LT: The response must be a list of items
  • HM: The type of the response must be a home object

And the regex conditional must be something like this (this is an example, please try to make your regex accurate):

if(/CRLTHM\s/.test(pm.info.requestName))

enter image description here

(In this image, NA is referring just to Not Authenticated)

Upvotes: 1

Related Questions