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.