skip to Main Content

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


  1. Chosen as BEST ANSWER

    I seem to have found the solution. I am now setting the token when the request is made:

    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, {  
                headers: {
                    Authorization: 'Bearer token'
                }, 
                data: requestBody
                
            }) 
    
            expect(response.status()).toBe(statusCode)
            return(response)
        }
    }
    

  2. 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 with access token.

    1 Launch Keycloak

    In here by docker-compose

    2 Install playwrite and dependency

    npm install -D @playwright/test
    npx playwright install
    

    3 Create Files

    enter image description here

    api/apiRequests.js

    const { expect } = require('@playwright/test');
    
    class ApiRequests {
        constructor(page) {
            this.page = page;
        }
    
        async postRequest(url, requestBody, expectedStatusCode) {
            const response = await this.page.request.post(url, {
                headers: { 'Content-Type': 'application/json' },
                data: requestBody
            });
    
            expect(response.status()).toBe(expectedStatusCode);
            return response;
        }
    
        async getToken(url, formBody, expectedStatusCode) {
            const response = await this.page.request.post(url, {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                data: formBody
            });
    
            expect(response.status()).toBe(expectedStatusCode);
            const responseJson = await response.json();
    
            return responseJson.access_token; // Return only the access token
        }
    }
    
    module.exports = { ApiRequests };
    

    testsapiRequests.js

    const { test: baseTest, expect } = require('@playwright/test');
    const { ApiRequests } = require('../api/apiRequests');
    
    // Define a base test fixture to include setting headers
    const test = baseTest.extend({
        authHeaders: async ({ page }, use) => {
            const apiReq = new ApiRequests(page);
            const url = 'http://localhost:8080/realms/master/protocol/openid-connect/token';
            const formBody = {
                grant_type: 'password',
                username: 'admin',
                password: 'admin',
                client_id: 'admin-cli'
            };
    
            const accessToken = await apiReq.getToken(url, new URLSearchParams(formBody).toString(), 200);
            await use({
                'Authorization': `Bearer ${accessToken}`
            });
        },
    });
    
    test.describe('API User Management Tests', () => {
        test('POST API Test for User Creation', async ({ page, authHeaders }) => {
            page.context().setExtraHTTPHeaders(authHeaders);
    
            const apiReq = new ApiRequests(page);
            const userUrl = 'http://localhost:8080/admin/realms/master/users';
    
            // Data for the new user
            const userData = {
                username: "user1",
                emailVerified: true,
                email: "[email protected]",
                firstName: "Super",
                lastName: "Mario",
                enabled: true
            };
    
            // Attempt to create user
            const createResponse = await apiReq.postRequest(userUrl, userData, 201);
            if (createResponse.status() === 409) {
                console.log("User already exists, test might need cleanup or handle existing user.");
            }
    
        });
    });
    

    playwright.config.js

    module.exports = {
        testDir: 'tests',
        testMatch: '**/*.test.js',
    };
    

    4 Test

    npx playwright test
    

    enter image description here

    5 Result

    user1 is created
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search