Global functions in postman

640 views Asked by At

I am writing this global function to assert the fields with the expected message and passing field and expectedMessage as the parameters.

   postman.setEnvironmentVariable("errorMessages", () => {
   var assertFieldErrorMessage = (field,expectedMessage) => {
   if (responseBody.has("data")) {
        pm.expect(pm.response.json().data.fieldErrors.get(field)).to.include(expectedMessage);
     } 
    };
 return {
    myPackage: {
        assertFieldErrorMessage
    }
};

This is how I am calling the function from my test script

   let errorMessages = eval(environment.errorMessages)();
   errorMessages.myPackage.assertFieldErrorMessage("email","Invalid value"); 

And this is what the response body looks like:

      "data": {
    "globalErrors": [],
    "fieldErrors": {
        "email": [
            "Invalid value for - "
]
    }
}

Having hard time to assert the fields in fieldErrors without hard coding them. What's going wrong in this?

1

There are 1 answers

0
Andrew Cressman On

Use:

pm.expect(pm.response.json().data.fieldErrors[field]).to.include(expectedMessage);

Instead of:

pm.expect(pm.response.json().data.fieldErrors.get(field)).to.include(expectedMessage);