Skip to content

🧰 Utility Files - Full Code with Explanations

🧰 Utility Files - Full Code with Explanations

This document explains the purpose and usage of each utility file in the framework. Each section includes full source code followed by a description.

1. getSharedApiContext.ts

import { request } from '@playwright/test';

import type { APIRequestContext } from '@playwright/test';

let apiContextInstance: APIRequestContext | null = null;

export async function getSharedApiContext(): Promise<APIRequestContext> {
  if (!apiContextInstance) {
    apiContextInstance = await request.newContext({
      baseURL: process.env.API_URL,

      extraHTTPHeaders: {
        Authorization: `Bearer ${process.env.BEARER_TOKEN}`,
      },
    });
  }

  return apiContextInstance;
}

export async function disposeSharedApiContext() {
  if (apiContextInstance) {
    await apiContextInstance.dispose();

    apiContextInstance = null;
  }
}

Explanation:

This file provides a singleton API request context (APIRequestContext) shared across tests. It uses the base URL and bearer token from the .env file to authorize API calls. It also supports disposal to prevent stale sessions.

2. resetBearerToken.ts

import fs from 'fs';

import path from 'path';

const envFilePath = path.resolve(__dirname, '../.env');

const envFile = fs.readFileSync(envFilePath, 'utf8');

const envVars = envFile.split('\n');

const updatedEnvVars = envVars.map((line) => {
  if (line.startsWith('BEARER_TOKEN=')) {
    return 'BEARER_TOKEN=';
  }

  return line;
});

fs.writeFileSync(envFilePath, updatedEnvVars.join('\n'), 'utf8');

Explanation:

This script clears the BEARER_TOKEN in the .env file by overwriting its value. Useful for invalidating stored tokens during cleanup or before regeneration.

3. getFilePath.ts

import * as path from 'path';

import { fileURLToPath } from 'url';

// @ts-ignore

const __filename = fileURLToPath(import.meta.url);

const __dirname = path.dirname(__filename);

export function getFilePath(fileName: string): string {
  const env = process.env.NODE_ENV || 'stg';

  const filePath = path.resolve(
    __dirname,
    `../../test-data/${env}/${fileName}`,
  );

  return filePath;
}

Explanation:

Generates an absolute path to a file in the test-data folder for the current environment. It ensures file access is scoped properly per environment (dev, stg, etc.).

4. getTestData.ts

import * as fs from 'fs';

import * as path from 'path';

import { fileURLToPath } from 'url';

// @ts-ignore

const __filename = fileURLToPath(import.meta.url);

const __dirname = path.dirname(__filename);

export function getTestData(element: string, fileName: string): any {
  const env = process.env.NODE_ENV || 'stg';

  const filePath = path.resolve(
    __dirname,
    `../test-data/${env}/${element}/${fileName}`,
  );

  try {
    const data = fs.readFileSync(filePath, 'utf-8');

    return JSON.parse(data);
  } catch (error) {
    console.error(`Error reading test data file: ${filePath}`, error);

    throw error;
  }
}

Explanation:

Reads a JSON file based on folder structure: /test-data/{env}/{element}/{fileName}. Converts the JSON content to an object for use in tests. Handles errors gracefully.

5. credentials.ts

import 'dotenv/config';

export const automation_user_email = (): string | undefined => {
  return process.env.AUTOMATION_USER_EMAIL;
};

export const automation_user_password = (): string | undefined => {
  return process.env.AUTOMATION_USER_PASSWORD;
};

Explanation:

Simple helpers that read the automation user credentials from environment variables.

6. updateSecret.ts

import * as fs from 'fs';

import * as path from 'path';

const envFilePath = path.resolve(__dirname, `../${process.env.NODE_ENV}`);

const newSecret = process.argv[2];

if (!newSecret) {
  console.error('No secret provided.');

  process.exit(1);
}

const envFile = fs.readFileSync(envFilePath, 'utf8');

const envVars = envFile.split('\n');

const updatedEnvVars = envVars.map((line) => {
  if (line.startsWith('BEARER_TOKEN=')) {
    return `BEARER_TOKEN=${newSecret}`;
  }

  return line;
});

fs.writeFileSync(envFilePath, updatedEnvVars.join('\n'), 'utf8');

Explanation:

Command-line utility to update the BEARER_TOKEN in the corresponding .env.{env} file. You pass the new token as an argument:  

node updateSecret.js NEW_TOKEN_VALUE

7. obtainUrl.ts

export class ObtainUrl {
  static readonly baseUrl = process.env.BASE_URL;
}

Explanation:

Encapsulates reading the BASE_URL from the environment. Used for navigating to the correct environment in UI tests.

8. validateExcelSheets.ts

import xlsx from 'xlsx';

import * as fs from 'fs';

import * as path from 'path';

export function validateRequiredSheets(
  filePath: string,
  requiredSheets: string[],
): void {
  if (!fs.existsSync(filePath)) {
    throw new Error(`File not found: ${filePath}`);
  }

  const workbook = xlsx.readFile(filePath);

  const sheetNames = workbook.SheetNames.map((name) =>
    name.trim().toLowerCase(),
  );

  for (const expected of requiredSheets) {
    if (!sheetNames.includes(expected.toLowerCase())) {
      throw new Error(`Missing required sheet: "${expected}"`);
    }
  }
}

Explanation:

This utility validates whether an Excel workbook contains all required sheets. Throws a clear error if a sheet is missing. Used in UI tests to verify report structure.

Back to top