What is the most effective way to implement an API method using Playwright to automate testing of an API that requires a token passed in a custom header property named 'x-my-api-token'?
This is my implementation code:
import { request, test, APIRequestContext } from "@playwright/test"
class DataApi {
constructor(private context: APIRequestContext) { }
public async getDataForEntity(token: string, entityId?: string): Promise<JSON> {
const response = await this.context.get(`https://api.example.com/activities/${entityId}`, {
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
'x-my-api-token': token
},
});
return await response.json();
}
}
When running this test code, the token passes to the Authorization header property, but the 'x-my-api-token' property is not included in the request header.
test("Data API", ({page}) => {
let dataApi: DataApi;
test.beforeAll(async () => {
dataApi = new DataApi(request);
});
const token = "sample_token";
const entityId = "12345";
test.step("should fetch data for an entity", async () => {
const data = await dataApi.getDataForEntity(token, entityId);
console.log(data);
});
});
I've also attempted using page.setExtraHTTPHeaders, but the result remains the same.
test("should fetch data for an entity", async ({page}) => {
page.setExtraHTTPHeaders{
'x-my-api-token': token
}
const data = await dataApi.getDataForEntity(token, entityId);
console.log(data);
});