Advanced Playwright TypeScript Tutorial | Code Generation | Part II | LambdaTest

:rocket: Hello folks! :rocket: Want to level up your testing game? :dart:

In our latest video, we dive deep into Playwright’s code generation! Learn how to:

:white_check_mark: Generate code with ease

:white_check_mark: Unlock powerful benefits

:white_check_mark: Avoid common pitfalls

:white_check_mark: Master usage for maximum efficiency

Watch now and start optimizing your testing workflow today! :desktop_computer::fire:

This tutorial is fantastic—really helps dive deeper into Playwright and TypeScript!

I’d also like to add a tip for Recording and Customizing Playwright Scripts:

Playwright offers a powerful code generation tool to record user interactions and create TypeScript scripts.

Here’s how to get started:

1. Use the Playwright CLI:

npx playwright codegen

2. Perform the desired actions in the browser while it records.

3. Save the generated script as a .ts file and customize it further with advanced features:

await expect(page.locator('selector')).toHaveText('Expected Text');

  • Add assertions:

await expect(page.locator('selector')).toHaveText('Expected Text');

  • Use custom helper functions for cleaner, reusable code snippets.

Finally, integrate the customized script into a test runner like Jest or Playwright Test to streamline your workflow.

Looking forward to more tutorials like this—great stuff for mastering Playwright!

This is such an insightful thread!

For larger projects, you can streamline your workflow by creating code templates to dynamically generate Playwright scripts based on input parameters.

Here’s how:

  1. Define a TypeScript code template as a string:
const template = `
import { test, expect } from '@playwright/test';

test('Dynamic Test - ${testName}', async ({ page }) => {
  await page.goto('${url}');
  // Add actions dynamically
  ${actions.join('\n')}
});
`;

2. Replace placeholders (${testName}, ${url}, ${actions}) with the required data dynamically.

3. Save the script programmatically** using Node.js:

const fs = require('fs');
fs.writeFileSync('tests/generatedTest.ts', template);

This approach is incredibly helpful when scaling test automation, especially when handling repetitive or parameterized test cases. It ensures consistency and saves time!

Advanced Script Generation with Custom Playwright Plugins

Leverage Playwright’s API and custom plugins to generate scripts programmatically:

  • Create a Playwright plugin to intercept and log actions:
class ScriptLogger {
  constructor() {
    this.logs = [];
  }
  logAction(action: string) {
    this.logs.push(action);
  }
  generateScript() {
    return this.logs.join('\n');
  }
}
  • Integrate it with Playwright:
const logger = new ScriptLogger();
page.on('request', (req) => logger.logAction(`await page.goto('${req.url()}');`));
// Add more event listeners for clicks, inputs, etc.

Export the script to a TypeScript file and refine it for advanced scenarios.