I have created a POST request to generate a token for myself. Next, I wrote the code for assertion using pm.test(), and it’s working. Following that, I sent another request via pm.sendRequest(). As a result of this request, I am receiving a response but not able to assert it.
I should be able to assert a response if I am receiving one.
There are five fields in the body: grant_type, client_id, client_secret, refresh_token, and redirect_uri
Here is the code for the tests:
pm.test(“Generate Token”, function () {
pm.response.to.have.status(200);
pm.response.to.have.status(“OK”);
});
var access_token = “abcd”;
var options1 = {
‘method’: ‘GET’,
‘url’: ‘example.com’,
‘header’: {
‘Authorization’: access_token,
‘Cookie’: ‘abcd’
}
};
pm.sendRequest(options1, function (error, response) {
response.to.have.status(400)
pm.test(“T001”, function () { //pm.sendRequest(options1, function (error, response) {
// var res = response.json();
// console.log(res);
pm.response.to.have.status(400);
// });
});
});
There are various ways to do this, but normally you would retrieve the token via the built-in authorisation options which includes OAuth2.
You can also use a pre-request script.
You could also retrieve the token via a normal request and then use the tests tab to set an environment or collection variable to use in the next request.
The point is that you aren’t usually testing the token aspect. You are testing the next request. Therefore, I would have this part as a normal request in Postman and the authentication should either be a pre-request, use the built- in authorisation or be a completely separate step.
I think the problem with your code is that when you use sendRequest, it’s not using the pm.response function, but a raw response.
On another side note. Those secrets really ought to be environment variables.
I say environment as you can then set the variables as secret so they are only available locally to you.
They don’t get uploaded to the Postman cloud and won’t be included if you export the collection to load into a code repository to use in a continuous integration tool.
You then need to send those variables as part of the pipeline or command line.