In my test I need to make an API request that requires a bearer token. I have managed to do this with a static, pre-defined token, but I need to get a new token each time via a GET request and this needs to be done at the time the test runs. I can get this token, but can’t work out how to set it in the extraHTTPHeaders
. This is what I currently have:
Spec:
const { test, expect } = require('@playwright/test');
const { ApiRequests } = require('../api/apiRequests.js');
test.use({
extraHTTPHeaders: {
Authorization: 'Bearer token'
}
})
test("My Test", async({ page }) => {
const apiReq = new ApiRequests(page)
await apiReq.postRequest('apiURL', requestBody, 200)
})
apiRequests.js:
const { expect } = require('@playwright/test');
export class ApiRequests {
constructor(page) {
this.page = page
}
async postRequest(url, requestBody, statusCode) {
const response = await this.page.request.post(url, {
data: requestBody
})
expect(response.status()).toBe(statusCode)
return(response)
}
}
So I want to be able to do what the test.use block is doing within the test block.
2
Answers
I seem to have found the solution. I am now setting the token when the request is made:
apiRequests.js:
You can get the token, and set the extra header every POST call instead of static token.
Demo
Using keycloak v24 and get
access token
and create user withaccess token
.1 Launch Keycloak
In here by
docker-compose
2 Install playwrite and dependency
3 Create Files
api/apiRequests.js
testsapiRequests.js
playwright.config.js
4 Test
5 Result
user1
is created