Writing Tests for Postman
Updated on 28 Dec 2018
Postman is great for development work with API’s, but we can also use it to add some tests. I.e. expected vs actual just like phpUnit.
Postman tests are written in JavaScript, and the synopsis is
pm.test("My Test Name", function () {
...test_code...
});
pm.response
The postman test code starts with a pm.response
and branches out from there. Response details are stored in the following formats.
- pm.response.code:Number
- pm.response.reason():Function → String
- pm.response.headers:HeaderList
- pm.response.responseTime:Number
- pm.response.text():Function → String
- pm.response.json():Function → Object
Additional information can be found on the Postman Sandbox API reference page.
pm.expect
is a generic assertion function. Underlying this is the ChaiJS expect BDD library. Using this library, it is easy to write tests where the syntax becomes readable.
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("this is from an open method");
});
Natural language asserts
ChaiJS library uses a natural language to describe the asserts. Here are some of the words we can use.
- to
- be
- is
- have
- include
- not
Here are a few more examples of using the asserts.
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Content-Type is present", function () {
pm.response.to.have.header("Content-Type");
});
Testing JSON
Based on what we have seen already, we might be able to see if we have a JSON response.
pm.test("We have JSON body", function () {
pm.response.to.have.jsonBody()
});
We can even check inside the JSON response for expected values
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.name).to.eql('brent');
});