For API tests I have to get a token first. Getting a token works with the following code:
test('Get accesstoken', async({request}) => {
const response = await request.post('https://...', {
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
data: new URLSearchParams({
"client_id": "...",
"scope": "..",
"grant_type": "client_credentials",
"client_secret": ".."
}).toString()
});
expect(response.status()).toBe(200);
const resBody = JSON.parse(await response.text());
const token = resBody.access_token;
expect(resBody.token_type).toBe("Bearer")
console.log(await token);
})
Now I have to save/store the token so that, when I execute the API in another test, I can use the saved token for authentication.
I found some examples on how to use the .env file but not on how to save varables there (or somewhere else).
Can someone provide me with some example code (Typescript) on how to save a variable and then how to retrieve the value.
I tried saving the variable token in the .env
file but could not find code on how to do that.
You should think of .env files as holding default declarations for your env variables. You can't dynamically set them from those files, but instead give them a default value. Perhaps this is an empty string, or something else.
Setting your token can be done directly in your API code if you wish. Something like:
expect(response.status()).toBe(200);
const resBody = JSON.parse(await
response.text());
const token = resBody.access_token;
expect(resBody.token_type).toBe("Bearer");
process.env.TOKEN = token;
console.log(await token);
Of course, my env variable name is just an example name, and you should change. It's as simple as that. Your .env file would give this TOKEN variable a default value, and it would set to your returned token in the code above.
Calling this in your tests can be added to your global setup, or project setup, or even a hook, so it's always available!
Remember, you will need dotenv installed for this.