Postman Test Scripts

For my postman project,testscript template are same for most requests.I don’t want to maintain it all requests.

I want to keep all test assertions inside like a method and need to call that method inside the requests wherever required.

Any solution for this

My Testscript template is
image

Hi @rajeswariramar. Welcome to the Postman Community!

If you add these test scripts at the collection level, it’ll run against every request in that collection.

1 Like

If you want to create a method to maintain some control over when the code is executed (instead of for every request if its set at the collection level), then you can use something similar to the following.

You need to initialize a variable at a global level (just define the variable without LET, CONST or VAR) with your function inside.

You will need to pass “pm” as an argument to the function if you intend to utilize Postman functions (which as you want to run tests, you will need to do).

The same applies if you want to access the pm.response method in your function.

utils = {
    statusCode: function (pm) {
        pm.test("Status code is 200", () => {
            pm.response.to.have.status(200);
        })
        return 'hello';
    },
    response: function (pm) {
        console.log(pm.response.json());
        return 'hello';
    }
};

You can then call these functions in your tests tab.

utils.response(pm);
utils.statusCode(pm);

image

To make it more re-usable, you may want to consider extending the arguments with customizable parameters.

utils = {
    statusCode: function (pm, code) {
        pm.test(`Status code is ${code}`, () => {
            pm.response.to.have.status(code);
        })
        return 'hello';
    }
};

Then calling it using…

utils.statusCode(pm, 200);

If I set the status code to 300, you can see that it errors.

utils.statusCode(pm, 300);

image

1 Like