如何在 typescript Playwright 中传递自定义标头属性?

问题描述 投票:0回答:1

使用 playwright 自动测试 API,该 API 需要在名为“x-my-api-token”的自定义标头属性中传递令牌。使用这样的自定义属性实现 API 方法的最有效方法是什么?

这是我写的代码。

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

运行此测试代码会将令牌传递给 Authorization 标头属性,但请求标头中不存在“x-my-api-token”属性。

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

我也尝试过使用 page.setExtraHTTPHeaders 但我得到了相同的结果。

    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);
    });
typescript automated-tests ui-automation playwright playwright-typescript
1个回答
0
投票

自定义标题对我来说效果很好:

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

test("Allows custom header", async ({request}) => {
  const res = await request.get("https://httpbin.org/get", {
    headers: {
      Accept: "application/json",
      "x-my-api-token": "42",
    },
  });
  const data = await res.json();
  expect(data.headers['X-My-Api-Token']).toBe("42");
});

输出:

$ npx playwright test pw1.test.js

Running 1 test using 1 worker

  ✓  1 pw1.test.js:3:1 › Allows custom header (539ms)

  1 passed (963ms)

请分享一个可以执行以产生错误的最小的、可重现的示例

© www.soinside.com 2019 - 2024. All rights reserved.