Playwright + JS · Lesson 11 of 35

0/35 done

Module 11: JavaScript for Test Automation

11. JavaScript Design Patterns for Test Automation

15 minlesson

Try it yourself

Implement buildAuthHeader:

  1. Accept user object with token property.
  2. If token is missing, throw an Error("Missing auth token").
  3. Return { Authorization: Bearer ${user.token} }.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

Centralized Configuration & Constants

Never hardcode raw timeouts or base URLs inside test files:

javascript
// config/constants.js
export const TIMEOUTS = Object.freeze({
  SHORT: 5000,
  MEDIUM: 15000,
  LONG: 30000,
});

export const ENVIRONMENTS = {
  staging: {
    baseUrl: "https://staging.targetqa.com",
    apiUrl: "https://api.staging.targetqa.com",
    defaultTimeout: TIMEOUTS.MEDIUM,
  },
  production: {
    baseUrl: "https://targetqa.com",
    apiUrl: "https://api.targetqa.com",
    defaultTimeout: TIMEOUTS.LONG,
  },
};

Utility Classes & Helper Functions

javascript
export class StringFormatter {
  static extractOrderId(text) {
    const match = text.match(/Order #(\d+)/);
    if (!match) throw new Error(`Order ID not found in text: ${text}`);
    return match[1];
  }
}

Key Takeaways & Walkthrough Summary

Welcome to Phase 2! Here we connect core JavaScript directly to automation. In this lesson, we design structured test data objects, centralized configuration files, constants, and utility classes so your tests are clean, maintainable, and DRY. Let's get started!

Part of the Playwright + JS course (Playwright with JavaScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why use Object.freeze() for constants in JavaScript?

Object.freeze() prevents accidental modifications to constant objects (like modifying timeouts) at runtime.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

JavaScript
Skip