Tips for sending a custom header property using TypeScript with Playwright

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);
    });

Answer №1

My experience with custom headers has been positive:

import {assert, test} from "@playwright/test"; // ^1.42.1

test("Testing Custom Headers", async ({request}) => {
  const res = await request.get("https://httpbin.org/get", {
    headers: {
      Authorization: "Bearer token123",
      "x-custom-header": "value",
    },
  });
  const data = await res.json();
  assert(data.headers["X-Custom-Header"]).toBe("value");
});

Result:

$ npx playwright test custom_header_test.js

Running 1 test using 1 worker

  ✓  1 custom_header_test.js:3:1 › Testing Custom Headers (543ms)

  1 passed (957ms)

Playwright automatically capitalizes the header names, as is anticipated.

Please provide a minimal reproducible scenario that can be run to reproduce the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Blurry text issue observed on certain mobile devices with Next.js components

There continues to be an issue on my NextJS page where some text appears blurry on certain mobile devices, particularly iPhones. This problem is only present on two specific components - both of which are interactive cards that can be flipped to reveal the ...

Leverage the power of react-redux useSelector with the precision of TypeScript

When attempting to utilize the new useSelector hook (shown in the example below) from react-redux in TypeScript, an error is encountered indicating that the function does not exist: Module '"../../../node_modules/@types/react-redux"' has no expo ...

Leverage third-party extensions instead of ionic-native plugins in your Ionic 2

Currently, I am utilizing a Cordova plugin from GitHub that is not accessible in Ionic Native. However, I have encountered an issue. How can I effectively use non-Ionic-Native plugins in Ionic 2? I attempted the following: declare var myPlugin: any; my ...

Tips for maintaining the current object's status while utilizing ngFor in Angular

The JSON data provided is structured as follows. [ { "route":"vehicle", "next-route":"driver", "isActive":false }, { "title":"Driver", "route":"driver ...

Arranging Select Dropdown Options in a Specific Order using Angular 7 and Typescript

My select dropdown is populated dynamically with options fetched from a service using *ngFor. I am looking to customize the order of these options. Can this be achieved through Angular code? The array structure is as follows: console.log(this.paymentTyp ...

Does having an excessive amount of variable declarations result in a noticeable decline in performance?

One thing I notice for the sake of readability is that I tend to create new variables for data that I already have on hand. I'm curious, does this impact performance significantly? Here's an example of what I mean: const isAdult = this.data.per ...

A loop in JavaScript/TypeScript that runs precisely once every minute

Here is a snippet of my code: async run(minutesToRun: number): Promise<void> { await authenticate(); await this.stock.fillArray(); await subscribeToInstrument(this, this.orderBookId); await subscribeToOrderbook(this, this.orderBookId ...

Exploring the use of Jest for testing delete actions with Redux

I've been working on testing my React + Redux application, specifically trying to figure out how to test my reducer that removes an object from the global state with a click. Here's the code for my reducer: const PeopleReducer = (state:any = init ...

Challenges with type checking in Angular TypeScript arise when attempting to import TensorFlow into a web worker

I have been experimenting with incorporating tensorflow/tfjs (TF) into a web-worker within an angular project. The process of creating a web-worker using the ng generate worker command has been successful. Importing TF in a component works without any is ...

I'm experiencing issues with my TypeScript compiler within my Next.js v14 project

I am working on a project using next.js version 14 and typescript v5. After installing these dependencies, I have noticed that the typescript compiler is not detecting errors related to types as expected. For example, when defining props for a component ...

How to troubleshoot: trying to assign '{ source: string; }' to type 'string' is not valid

I'm encountering an issue that seems like it should have a simple solution, but I can't seem to find any explanations on how to fix it. I'm working with Next.js and Typescript to create a component that displays an image and uses hooks to ma ...

Discover the step-by-step process for moving data between collections in MongoDB

I am currently working on nestjs and have two collections, one for orders and the other for payments. My goal is to retrieve a single entry from the orders collection and save that same entry into the payments collection. Below is the code for the service ...

Is there a way to verify if a value is undefined before including it as an object field?

I'm currently working on an Angular project and I have a query regarding TypeScript. It's about correctly handling the scenario where a field should not be included in an object if its value is undefined. In my code, I am initializing an object ...

Using the -t or --testNamePattern in Jest will execute all tests

Currently, I have set up my testing framework using jest and ts-jest based on the guidelines provided by the ts-jest documentation. When I execute the command yarn test --listTests, I can identify the specific test file I intend to run: processNewUser.ts ...

A guide on assigning specific (x, y) coordinates to individual IDs within the tree structure

When attempting to calculate the positions of each ID in order to arrange them hierarchically on the canvas, I encounter some challenges. Whether it's organizing them into a tree structure or multiple trees resembling a forest, one restriction is that ...

Facing issues with updating a dynamic input form array in Angular

For my Angular-12 project, I am currently working on implementing a dynamic input fields FormArray within a Reactive Form to handle updates. Below is the code snippet: Interface: export interface IResponse<T> { message: string; error: boolean; ...

Using the ternary operator in React to implement inline styles

Within my React/Typescript project, I aim to dynamically exhibit a color based on the presence or absence of a value in payload[1]. In the code snippet below, note the usage of an inline style tag. <li className="recharts-tooltip-item" style={ ...

Accessing information from RESTful Web Service with Angular 2's Http functionality

I am currently working on retrieving data from a RESTful web service using Angular 2 Http. Initially, I inject the service into the constructor of the client component class: constructor (private _myService: MyService, private route: Activat ...

Simplify typing in TypeScript using default generic parameters

Imagine I came across the following object: const inquiries = { whoCreatesIssues: { options: { sameTeam: { id: 'SAME_TEAM' }, management: { id: 'MANAGEMENT' ...

Error in Typescript React Component: Type 'Element' is not compatible with the parameter type

It's puzzling why there is an error here, to be honest, I can't figure it out. https://i.sstatic.net/Gm2Uj.jpg generateLinkSetsForNation function generateLinkSetsForNation(nation: Nation, enterprises: Array<Enterprise>) { let enterpri ...