Search code examples
playwright

Unable to read extraHTTP headers from custom config in my test file


I have created custom config file in Playwright with extraHTTPHeaders as below which list content-type and *Authorization. I am expecting the headers should be automatically passed into to my request but I keep on getting .

const { devices, chromium } = require('@playwright/test');
// const { getToken } = require("./helper");
use: {
    /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
    actionTimeout: 0,
    // headless: true,
    /* Base URL to use in actions like `await page.goto('/')`. */
    baseURL: 'https://connect.dev.morinc.com/api/eds',
    extraHTTPHeaders: {
      Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
      'Content-Type': "application/json"
    },
    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry',
  },

Below is my test file where I am expecting headers to be automatically be picked up from custom config file but I am getting

const { getToken } = require("../../auth0");
import { faker } from '@faker-js/faker';
const { entityTypes } = require("../../global.js");

test.beforeAll(async() => {
  await getToken();
})

test.describe('Create Entity', async() => { 
  test("Create an entity", async ({baseURL, request}) => {
    const requestBody = {
      data: {
        query: `
          mutation CreateEntity($name: String!, $type: EntityType, $active: Boolean, $identifiers: [String]) {
            createEntity(name: $name, type: $type, active: $active, identifiers: $identifiers)  {
              name
              type
              active
              id
              identifiers
              items
          }
        }`,
        variables: {
          name: faker.name.fullName(),
          type: entityTypes.corporate,
          active: true,
          identifiers: []
        }
      }
      };
    const response = await request.post(baseURL, requestBody);
    const responseBody = await response.json();
    //Assertions
    expect(response.status()).toBe(200);
    expect(responseBody.data.createEntity.name).toBe(requestBody.data.variables.name);
    expect(responseBody.data.createEntity.type).toBe(requestBody.data.variables.type);
    expect(responseBody.data.createEntity.active).toBeTruthy();
    expect(responseBody.data.createEntity.id).toBeTruthy();
    expect(responseBody.data.createEntity.identifiers).toHaveLength(0);
    expect(responseBody.data.createEntity.items).toBe(null);
  });
}); 

I am running npx playwright test --config=api.config.js command to run my test to use my custom config file over default one.

I am getting error SyntaxError: Unexpected end of JSON input on below code line*** const responseBody = await response.json();

Is this correct way to read headers from custom config file? Why am I getting error?

Below is the function definition of getToken defined in 'auth0.js'

require("dotenv").config({path: ".env.dev"});
let auth0Credentials = JSON.parse(process.env.AUTH0_CONFIG)
let userCredentials = JSON.parse(process.env.USERS_CREDENTIALS)


async function getToken() {
  const tokenExpiration = process.env.ACCESS_TOKEN_EXPIRATION;
  const storedToken = process.env.ACCESS_TOKEN;
  if (
    storedToken &&
    tokenExpiration &&
    new Date(tokenExpiration) > new Date()
  ) {
    return storedToken;
  }
  const credentials = {
    client_id: auth0Credentials.client_id,
    client_secret: auth0Credentials.client_secret,
    audience: auth0Credentials.audience,
    grant_type: auth0Credentials.grant_type,
    username: userCredentials.q4admin,
    password: userCredentials.password,
  };

  const url = auth0Credentials.oauthURL;

  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(credentials),
  };
  
  const response = await fetch(url, options);
  const json = await response.json();
  const expiresIn = json.expires_in || 0;
  const accessToken = json.access_token || "";

  process.env.ACCESS_TOKEN_EXPIRATION = new Date(Date.now() + expiresIn * 1000).toISOString();
  process.env.ACCESS_TOKEN = accessToken;
  return accessToken;
}

module.exports = {getToken}

Solution

  • I think the Playwright_Config.ts file is initialised before the execution of any tests. So the Authorization is being set as null. You can set the Auth inside every "request.post(baseURL, requestBody)" like below .

    request.post(baseURL, requestBody, headers: { Authorization: Bearer ${process.env.ACCESS_TOKEN}, 'Content-Type': "application/json" } );