Skip to content

Reusable Code

Ben Weese edited this page Jul 6, 2019 · 7 revisions

The below example is a way to use reusable code. You can store a common test inside a function and then store that function in the Environmental Variable. You want this to be the first call in the collection so that all other calls after can use the functions from the Environmental Variable. The best place for this is inside the pre-request scripts for the call.

Example

Here we create a function that is then stored in the environmental variable. This is so we can then call this from any following test. This must be in the first test of the collection or collection folder.

postman.setEnvironmentVariable("commonTests", () => {

These are test that are ran on every call of the commonTest.

pm.test("Response time is less than 200ms", function () {
   pm.expect(pm.response.responseTime).to.be.below(200);
});
pm.test(environment.requestName + "Response must be valid and have a body", function () {
   pm.response.to.be.json; // this assertion checks if a body  exists
});

We then create a function within commonTest for the Successful test we will run.

var positive = () => {
  pm.test("Status code is 200", function () {
     pm.response.to.have.status(200);
  });
  pm.test(environment.requestName + "Response does not error", function () { 
     pm.response.to.not.be.error; 
     pm.response.to.not.have.jsonBody("error"); 
  });        
}

This is a function for the negative test, or the test we want to fail.

var negative = (arg=400) => {
     if(arg===400){
        pm.test("Status code is 400", function () {
            pm.response.to.have.status(400);
        });
     }else if(arg===404){
        pm.test("Status code is 404", function () {
            pm.response.to.have.status(404);
        });
     }else if(arg===500){
        pm.test("Status code is 500", function () {
            pm.response.to.have.status(500);
        });
     }
     pm.test(environment.requestName + "Has correct schema", function() {
        pm.response.to.be.error;
     });        
}

Lastly we return the functions, so we can call them from outside the environmental variable

return {
  testType: {
    positive,
    negative
    }
};
});

For positive test

eval(environment.commonTests)().testType.positive();
const jsonData = pm.response.json();

Below is checking that the data has the correct schema. If we wanted to check correct data we could just add .and.eql(data);

pm.test("Has correct schema", function() {
       pm.expect(jsonData.str).to.be.a("string");
       pm.expect(jsonData.numArray[0]).to.be.a("number");
       pm.expect(jsonData.numArray[1]).to.be.a("integer");
       pm.expect(jsonData.bool).to.be.a("boolean");
});

For negative test

eval(environment.commonTests)().testType.negative();
const jsonData = pm.response.json();
pm.test("Has correct schema", function() {
      pm.expect(jsonData.error).to.be.a("string");
});
Clone this wiki locally