I have tried searching for this use case but not able to find one. I will try to explain the scenario I am trying to test as detailed as possible
There are several APIs in my application and all the APIs require an access token as a header. I would like to create a test where it does the following series of steps:
- Trigger the ‘XYZ’ API call
- If the response has the message “Token has expired”
* Trigger the Login API
* Grab the accessToken from the response and save it as a collection variable - Run the same ‘XYZ’ API again
I have attached my script below:
//Create Login details as a variable beforehand
const loginApi = (
{
url: 'https://test.com/login',
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'raw',
raw: JSON.stringify(
{
"username": `${pm.globals.get('Username')}`,
"password": `${pm.globals.get('Password')}`
}
)
}
}
)
/*
Define if else condition
If the message is Token expired ("message": "Token expired"),
Call Login API
Save the token into a collection variable
Else
Save the token into the collection variable
*/
pm.test("Check if the response message contains 'Token expired'", function() {
var responseData = pm.response.json();
if (responseData.message.includes('Token expired')) {
pm.sendRequest(loginApi, (error, response) => {
//Parsing response data
var loginResponseData = response.json();
//Storing accessToken from response into a collection variable
var loginAccessToken = loginResponseData.accessToken;
pm.collectionVariables.set("loginAccessToken", loginAccessToken);
console.log("The login access token is " + loginAccessToken);
})
}
});
//Grab the current request ID and trigger the API again using the request ID
const currentRequestId = pm.info.requestId;
console.log("The request ID is " + currentRequestId);
postman.setNextRequest(currentRequestId);
If a token was expired, I was successfully able to generate the token and store it into the collection variable
However, the current API was not triggered again automatically to produce the 200 OK response. It just stays at the 401 Unauthorized screen with the message as “Token Expired”
When I hit Send again, I am getting a success response
Essentially I am trying to skip hitting the Send button 2 times, and I would like the XYZ API to automatically trigger again once it triggers the Login API.
Any help to resolve my issue would be greatly appreciated. Thanks in advance!!
PS: Unfortunately, I cannot share screenshots because it has sensitive information. I would be glad to provide more information if needed.