postman test examples
Example 1: postman test script get request code
tests["Status code is 200"] = responseCode.code === 200;
console.log(tests["Status code is 200"] = responseCode.code != 200)
Example 2: how do you test in postman
I mostly use preInstalled js testScripts in postman
in Tests tab. Basically test will execute after
response received for verification. So when I send
the request by clicking SEND postman runs the test
script and after response gives me test result
Some of the snippets I use:
Get an environment variable
Set an environment variable
Clear a environment variable
Clear a global veriable
Get a global variable
Set a global variable
Send a request
Response convert xml to json
Response time is less than
etc.
Example:
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
pm.test("response must be valid and have a body", function () {
pm.response.to.be.ok;
pm.response.to.be.withBody;
pm.response.to.be.json;
});
Example 3: postman test script get request code
postman.setEnvironmentVariable("key", "value");
const array = [1, 2, 3, 4];
postman.setEnvironmentVariable("array", JSON.stringify(array, null, 2));
const obj = { a: [1, 2, 3, 4], b: { c: 'val' } };
postman.setEnvironmentVariable("obj", JSON.stringify(obj));
postman.getEnvironmentVariable("key");
const array = JSON.parse(postman.getEnvironmentVariable("array"));
const obj = JSON.parse(postman.getEnvironmentVariable("obj"));
postman.clearEnvironmentVariable("key");
postman.setGlobalVariable("key", "value");
postman.getGlobalVariable("key");
postman.clearGlobalVariable("key");
tests["Body matches string"] = responseBody.has("string_you_want_to_search");
tests["Body is correct"] = responseBody === "response_body_string";
const data = JSON.parse(responseBody);
tests["Your test name"] = data.value === 100;
tests["Content-Type is present"] = postman.getResponseHeader("Content-Type");
tests["Content-Type is present"] = postman.getResponseHeader("Content-Type");
tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");
tests["Response time is less than 200ms"] = responseTime < 200;
tests["Response time is acceptable"] = _.inRange(responseTime, 100, 1001);
tests["Status code is 200"] = responseCode.code === 200;
tests["Status code name has string"] = responseCode.name.has("Created");
tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;