Check response header's value in Postman tests
Solution 1
I finally found the solution:
pm.test("Redirect location is correct", function () {
pm.response.to.have.header("Location");
pm.response.to.be.header("Location", "http://example.com/expected-redirect-url");
});
Solution 2
Here is another way of fetching the specific response header in Tests section ...
loc = pm.response.headers.get("Location");
Just in case, if the subsequent request(s) need the specific info, like header value, then you can also store/set it as environment variable as below, and reuse further
pm.environment.set("redirURL", loc);
var loc = null;
pm.test("Collect redirect location", function () {
pm.response.to.have.header("Location");
loc = pm.response.headers.get("Location");
if (loc !== undefined) {
pm.environment.set("redirURL", loc);
}
});
The advantage is - the value collected in the variable can be manipulated.
But it all depends on the situation. Like, you might want to extract and pre/post-process the redirect URL.
For example,
While running the test collection, you would like to collect the value in a variable and change it to point to the mock server's host:port.
Solution 3
HeadersList has the method has(item, valueopt) → {Boolean}
, so easiest way to check the header is:
const base_url = pm.variables.get("base_url")
pm.test("Redirect to OAuth2 endpoint", () => {
pm.expect(pm.response.headers.has("Location",`${base_url}/oauth2/`)).is.true
})
Lluís Suñol
Updated on July 06, 2021Comments
-
Lluís Suñol almost 3 years
I would like to check the value from a concrete response header ("Location") as Test Results in Postman. In the Postman's documentation I found examples of how to check the existance of headers with
pm.test("Content-Type is present", function () { pm.response.to.have.header("Content-Type"); });
But what I'm looking for is something like
pm.test("Location value is correct", function () { CODE HERE THAT CHECKS "Location" HEADER EQUALS TO SOMETHING; });