I have been trying to check certain fields in my response to see if they contain valid characters. Below is an example:
"Manufacturer": "MAJOR PHARMACEU"
I want to make sure that ONLY these characters are present (0-9, a-z, A-Z, “-”, “_”) if any other characters are present, I want to pass a FAILED message. I tried using the code below in the test section, but it is not returning the correct results:
var manufacturer = response.LineItems[0].Manufacturer;
if (/^[0-9a-zA-Z\-_]+$/.test(manufacturer) === true){
pm.test("Manufacturer field contains invalid characters");
}
else {
pm.test("Manufacturer field contains valid characters");
}
Any directions would be greatly appreciated.
Hi @lhuntsinger,
Assuming the response is JSON, you can make modifications to your code like this
let response = pm.response.json(),
manufacturer = _.get(response, 'LineItems.0.Manufacturer'); // similar to response.LineItems[0].Manufacturer
// In case manufacturer does not contain valid characters, this particular test will fail and you can view the test results in Tests tab
pm.test("Manufacturer field contains invalid characters", () => {
pm.expect(/^[0-9a-zA-Z\-_]+$/.test(manufacturer)).to.be.true;
});
You can go through the following links for examples and documentation on how to write test scripts in Postman. Also about the inbuilt libraries (Ex: Lodash)
https://learning.getpostman.com/docs/postman/scripts/test_scripts
https://learning.getpostman.com/docs/postman/scripts/test_examples
https://learning.getpostman.com/docs/postman/scripts/postman_sandbox/#commonly-used-libraries-and-utilities
1 Like