The Pragmatic Programmer

Appian, Pega, Java, DevSecOps, Quality Engineering

Automating Form Submission with Playwright and TypeScript

In this tutorial, we’ll continue our exploration of Playwright and TypeScript by automating the process of filling out and submitting a form on a website. This example will demonstrate how to interact with input fields, checkboxes, and buttons.

Prerequisites

Before you begin, make sure you have completed the initial setup outlined in the previous blog post.

Getting Started

1. Writing the Script

Create a new TypeScript file in your project directory, such as form_submission.ts. Open the file in your code editor and paste the following code:

import { chromium, Browser, Page } from 'playwright';

(async () => {
  // Launch the browser
  const browser: Browser = await chromium.launch();

  // Create a new browser context
  const context = await browser.newContext();

  // Create a new page
  const page: Page = await context.newPage();

  // Navigate to the form page
  await page.goto('https://www.example-form.com');

  // Fill out the form
  await page.fill('#name', 'John Doe');
  await page.check('#subscribe');
  await page.selectOption('#gender', 'male');

  // Submit the form
  await page.click('#submit-button');

  // Wait for the form submission to complete
  await page.waitForSelector('#success-message');

  // Capture a screenshot of the success message
  await page.screenshot({ path: 'form_submission.png' });

  // Close the browser
  await browser.close();
})();

2. Compiling and Running the Script

Compile the TypeScript code into JavaScript using the TypeScript compiler:

tsc form_submission.ts

Then, run the compiled script with Node.js:

node form_submission.js

The script will navigate to a form page, fill out the form with sample data, submit it, wait for the success message to appear, and capture a screenshot of the success message.

Customization

You can customize the script to interact with different types of form elements, handle error scenarios, or automate other interactions on web pages.

Conclusion

In this example, we demonstrated how Playwright and TypeScript can be used to automate the process of filling out and submitting a form on a website. This combination of technologies enables developers to efficiently automate various web interactions and streamline testing processes.

Feel free to build upon this example and explore Playwright’s extensive documentation to discover more features and use cases.

Happy automating!


Feel free to adjust the example and the explanation according to your preferences. This example showcases how to interact with form elements and perform actions like filling out fields, checking checkboxes, selecting options from dropdowns, and capturing screenshots of success messages.