11. TypeScript Design Patterns for Test Automation

Why Strong Typing Matters in Test Automation

In dynamic languages like JavaScript or Python, changing a field name in an API or form from user_email to userEmail causes dozens of runtime errors deep in your test runs. In TypeScript, your editor catches this instantly before you even trigger a browser session.

---

1. Test Data Interfaces & Type Safety

Define strict contracts for test payloads:
export interface UserCredentials {
  readonly email: string;
  readonly passwordHash: string;
  readonly role: "ADMIN" | "QA" | "VIEWER";
  readonly rememberMe?: boolean;
}

export interface ApiResponse<T> {
status: number;
message: string;
data: T;
}

---

2. Centralized Configuration Objects & Constants

Never hardcode URLs or magic timeouts inside tests:
export const TIMEOUTS = {
  SHORT: 5_000,
  MEDIUM: 15_000,
  LONG: 30_000,
} as const;

export interface EnvironmentConfig {
baseUrl: string;
apiUrl: string;
defaultTimeout: number;
}

export const ENV_CONFIG: Record<string, EnvironmentConfig> = {
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,
},
};

---

3. Utility Classes & Page Object Concepts

Group reusable actions and domain concepts into strongly typed utility classes:
export class StringFormatter {
  public static extractOrderId(text: string): string {
    const match = text.match(/Order #(\d+)/);
    if (!match) throw new Error(Failed to parse Order ID from text: ${text});
    return match[1];
  }
}

Task

  • Complete the UserProfile interface and buildAuthHeader function:
  • 1. Ensure UserProfile contains id (number), email (string), and optional token (string).
  • 2. The function buildAuthHeader returns { Authorization: `Bearer ${user.token}` } or throws if token is missing.
πŸ’‘Common doubts
Did you like the problem?
Lesson 11 of 36
TypeScript
Loading code editor…
Next