Facing issue while adding a proxy to the playwright Typescript based Framework?

  • How can they help you?

My issue is that, i am not able to work any api cases because of proxy. I have tried giving the proxy information at global level , project level and both global and project level. But unable to fix the issue.

My proxy url format is https://username:password@host:port.

Since i cannot copy the code from client system, i tried to manually create in my local system and shared the Test file,Utility class code &. Config file .

System info

  • Playwright Version: [v1.39.0]
  • Operating System: [Windows 11 Pro]
  • Browser: [All, Chromium]

Source code

Test File

import { test, expect, Route } from ‘@playwright/test’;
import { util } from ‘…/Util/util.spec’;

test.only(‘Get Api Test’, async ({ page }) => {
const utl=new util();
const response=await utl.sendGetRequest(‘any get api’);
console.log(response);
expect(response.status).toBe(200);
});

import { Locator, Page, expect, request } from “@playwright/test”;
import * as fs from “fs”;
import axios from ‘axios’;
import { AxiosResponse } from ‘axios’;

Utility Class

class util {

private request: any;
private page: any;

loadRequestPayloadFromJSON(filePath: string): any {
    var rawData: string = "";
    rawData = fs.readFileSync(filePath, "utf-8");
    return JSON.parse(rawData);
}

async checkAllAPIStatusCode(apiRequests: any[]) {
    for (const apiRequest of apiRequests) {
        const response = apiRequest.response();
        await expect(response.status).toBeOK();
    }
}

async sendGetRequest(url: string, /*authFile: string*/): Promise<any> {
    // var response: any = '';

    // response = await this.request.get(url
    // //     , {
    // //     headers: {
    // //         Accept: '*/*',
    // //         Authorization: authFile,
    // //     },
    // // }
    // );
    // return response;

    try {
        // Use the axios library to make an HTTP GET request
        const response = await axios.get(url);
        return response;
    } catch (error) {
        console.error('Error making GET request:', error);
        throw error; // You can handle the error as needed
    }
}

// async sendPutRequest(
//     url: string,
//     header: any,
//     req_filePath: string,
// ): Promise<any> {
//     var response: any = '';
//     const payload = this.loadRequestPayloadFromJSON(req_filePath);

//     response = await this.request.put(url, {
//         headers: header,
//         data: payload,
//     });
//     return response;
// }

async sendPostRequest(url: string, payload: any, customHeaders: Record<string, string> = {}): Promise<AxiosResponse> {
    try {
        // Define request configuration with custom headers
        const config = {
            headers: {
                ...customHeaders, // Include any custom headers passed from the test
            },
        };

        // Use axios to make an HTTP POST request with custom headers
        const response = await axios.post(url, payload, config);

        // Return the response object
        return response;
    } catch (error) {
        console.error('Error making POST request:', error);
        throw error; // You can handle the error as needed
    }
}

async sendPutRequest(url: string, payload: any, customHeaders: Record<string, string> = {}): Promise<AxiosResponse> {
    try {
        // Define request configuration with custom headers
        const config = {
            headers: {
                ...customHeaders, // Include any custom headers passed from the test
            },
        };

        // Use axios to make an HTTP PUT request with custom headers
        const response = await axios.put(url, payload, config);

        // Return the response object
        return response;
    } catch (error) {
        console.error('Error making PUT request:', error);
        throw error; // You can handle the error as needed
    }
}

}

export { util };

Config File

import { defineConfig, devices } from ‘@playwright/test’;

const globalProxy = {
proxy: {
server: ‘http://per-context’, // Placeholder string
}
};

/**

  • Read environment variables from file.

*/
// require(‘dotenv’).config();

/**

/
export default defineConfig({
testDir: ‘./tests’,
/
Run tests in files in parallel /
fullyParallel: true,
/
Fail the build on CI if you accidentally left test.only in the source code. /
forbidOnly: !!process.env.CI,
/
Retry on CI only /
retries: process.env.CI ? 2 : 0,
/
Opt out of parallel tests on CI. /
workers: process.env.CI ? 1 : undefined,

reporter: ‘html’,

use: {
/
Base URL to use in actions like await page.goto('/'). */

…globalProxy,
},

/* Configure projects for major browsers */
projects: [
{
name: ‘chromium’,
use: { …devices[‘Desktop Chrome’] ,
},

   // Other options you might have
},

// {
//   name: 'firefox',
//   use: { ...devices['Desktop Firefox'] },
// },

// {
//   name: 'webkit',
//   use: { ...devices['Desktop Safari'] },
// },

/* Test against mobile viewports. */
// {
//   name: 'Mobile Chrome',
//   use: { ...devices['Pixel 5'] },
// },
// {
//   name: 'Mobile Safari',
//   use: { ...devices['iPhone 12'] },
// },

/* Test against branded browsers. */
// {
//   name: 'Microsoft Edge',
//   use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
//   name: 'Google Chrome',
//   use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },

],

/* Run your local dev server before starting the tests */
// webServer: {
// command: ‘npm run start’,

// reuseExistingServer: !process.env.CI,
// },
});

or

Config file

// playwright.config.ts import { defineConfig, devices } from ‘@playwright/test’; export default defineConfig({ projects: [ { name: ‘chromium’, use: { …devices[‘Desktop Chrome’], }, }, ] });

  • What context can you share to increase the likelihood of someone replying to your question?

Basically, i need help with How i can handle proxy on client system while writing a API code using Playwright Typescript. I have gone through so many approaches with no luck.

Another approach using Request Fixture.

Test File
test(@API getUsers, async ({ request }) => {
const response = await request.get(https://jsonplaceholder.typicode.com/todos/1);
await new Promise(resolve => setTimeout(resolve, 5000)); // 5-second delay
await apiActions.verifyStatusCode(response);
//console.log(response);

//* Body Response Params and Body Response Headers are stored in single text file separated by #
// const responseBodyParams = (await apiActions.readValuesFromTextFile(`getUsers`)).split(`#`)[0];
// await apiActions.verifyResponseBody(responseBodyParams, await response.json(), `Response Body`);

// const responseBodyHeaders = (await apiActions.readValuesFromTextFile(`getUsers`)).split(`#`)[1];
// await apiActions.verifyResponseHeader(responseBodyHeaders, response.headersArray(), `Response Headers`);

});

Util Class

import { APIActions } from “…/Util/APIActions”;
import { test } from ‘@playwright/test’;

const apiActions = new APIActions();
import fs from ‘fs’;
import { APIResponse, expect } from ‘@playwright/test’;

export class APIActions {

async verifyStatusCode(response: APIResponse): Promise<void> {
    await expect(response, `200 Status code was not displayed.`).toBeOK();
}

async verifyResponseBody(expectedResponseBodyParams: string, responsePart: JSON, responseType: string): Promise<void> {
    let status = true;
    let fieldNames = `Parameter`;
    const headers = expectedResponseBodyParams.split("|");
    const responseToString = JSON.stringify(responsePart).trim();
    for (let headerKey of headers) {
        if (!(responseToString.includes(headerKey.trim()))) {
            status = false;
            fieldNames = fieldNames + `, ` + headerKey;
            break;
        }
    }
    expect(status, `${fieldNames} was not present in ${responseType}`).toBe(true);
}