Playwright + TS · Lesson 2 of 36

0/36 done

Module 2: Functions

2. Functions, Arrow Syntax & Modern Operators

12 minlesson

Your task

Complete the createTestUser function:

  1. Use object destructuring to extract username and role from input.
  2. Return a formatted string using template literals: "User: ${username} | Role: ${role}".

Write it in the editor, then press Check answer (Ctrl + Enter).

Function Declarations vs Arrow Functions

In Playwright test scripts, you will write arrow functions everywhere:

typescript
// Arrow function:
const buildUrl = (path: string): string => {
  return `https://targetqa.com${path}`;
};

Template Literals (${value})

Use backticks (`) instead of string concatenation (+`) to interpolate dynamic test data:

typescript
const userId = 104;
const locator = `//div[@data-user-id='${userId}']`;

Destructuring (Array & Object)

Playwright passes test fixtures using object destructuring:

typescript
// Destructuring object properties:
const user = { username: "admin", role: "lead", timeout: 5000 };
const { username, role } = user;

// Array destructuring:
const [firstItem, secondItem] = ["Chromium", "Firefox"];

Spread (...) & Rest (...rest) Operators

typescript
// Spread: copies or merges objects/arrays
const baseConfig = { headless: true, timeout: 30000 };
const testConfig = { ...baseConfig, browser: "firefox" };

// Rest: collects remaining arguments into an array
function logSteps(testName: string, ...steps: string[]) {
  console.log(`Running ${testName} with ${steps.length} steps`);
}

Key Takeaways & Walkthrough Summary

Functions are the building blocks of clean test automation. In this lesson, we will explore modern JavaScript functions, including arrow functions, callbacks, template literals, and destructuring. You will see how these features make your test code concise, reusable, and easy to read. Let's dive in!

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

Common Doubts & Lesson Q&A

Why does Playwright use test('...', async ({ page }) => {}) with curly braces?

That is object destructuring! Playwright's test runner passes an object containing all fixtures ({ page, context, browser, request }), and destructuring extracts only the ones you need.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

TypeScript
Skip