Articles

Getting Started with Playwright in JavaScript

2024-08-12·4 min read
Photo by Boitumelo on Unsplash

Development and testing can often feel like taming a herd of wild animals. Each browser behaves a little differently, throwing unexpected behaviors and unique quirks at us. Automated browser testing can make this task more manageable, but finding the right tool for the job is crucial. Enter Playwright—a modern, powerful, and reliable framework for testing web applications that supports multi-browser automation. If you’re new to Playwright and are wondering how to get started with it in JavaScript, you’ve come to the right place.

What is Playwright?

Developed by Microsoft, Playwright is an open-source Node.js library. It provides a single API for automated browser testing across major browsers like Google Chrome, Microsoft Edge, Firefox, and WebKit (the engine behind Safari). It’s designed for end-to-end testing, ensuring your application works smoothly in different environments.

Why Use Playwright?

Before diving into the setup and coding, it’s important to understand why Playwright should be your go-to tool for browser testing.

Cross-Browser Support

Playwright allows you to write tests that work on all major browser engines. This includes headless browsers, which can make your CI/CD pipeline more efficient.

Auto-wait and Web-First Assertions

Playwright automatically waits for the UI to be ready, which significantly reduces the chance of flakiness in tests. This ensures that your assertions are aligned perfectly with user interactions.

Network Interception

Playwright can intercept network activity, allowing you to mock API responses, measure performance, and test offline scenarios with ease.

Built-in Test Runner

Its built-in test runner integrates with JavaScript and TypeScript, making the test-writing experience smoother and more integrated.

Setting Up Playwright

Let's roll up our sleeves and set up Playwright in a JavaScript project.

Prerequisites

First, make sure you have Node.js installed on your machine. If not, download and install it from the official Node.js website.

Initialize Your Project

  1. Open your terminal or command prompt.
  2. Create a new project directory and navigate into it:
    mkdir playwright-example
    cd playwright-example
  3. Initialize a new Node.js project:
    npm init -y

Install Playwright

Now, you'll need to install Playwright via npm:

npm install playwright

Scaffold a Test

Let's create a test to check if we can log into a website successfully. Create a new file named example.test.js inside your project directory and add the following code:

const { chromium } = require("playwright")
;(async () => {
    const browser = await chromium.launch()
    const page = await browser.newPage()
    await page.goto("https://example.com/login")

    // Perform login
    await page.fill("#username", "myUsername")
    await page.fill("#password", "myPassword")
    await page.click("#login-button")

    // Verify login was successful
    await page.waitForSelector("#welcome-message")
    const welcomeMessage = await page.$("#welcome-message")
    console.log(await welcomeMessage.innerText())

    await browser.close()
})()

Running Your Test

Time to run the test you just wrote. In your terminal, run:

node example.test.js

If everything was set up correctly, you should be able to see the output of the welcome message printed on the console.

Photo by Samia Liamani on Unsplash

Enhancing the Test

Now that you have a basic test working, let's add some additional functionality to make it more robust and versatile.

Using Playwright Test Runner

Playwright comes with a test runner that can make managing multiple tests easier. Let’s set it up.

  1. Install Playwright Test package:

    npm install @playwright/test
  2. Create a new file named example.spec.js and move your test code into it. Modify your code to comply with Playwright Test format:

const { test, expect } = require("@playwright/test")

test("login test", async ({ page }) => {
    await page.goto("https://example.com/login")

    // Perform login
    await page.fill("#username", "myUsername")
    await page.fill("#password", "myPassword")
    await page.click("#login-button")

    // Verify login was successful
    await expect(page).toHaveSelector("#welcome-message")

    const welcomeMessage = await page.$("#welcome-message")
    console.log(await welcomeMessage.innerText())
})
  1. Run your tests using the Playwright Test runner:
    npx playwright test

You’ll notice the Playwright Test runner automatically generates a report and provides more meaningful output for your tests.

Advanced Features

Playwright is robust and comes with a variety of features that can help you create more sophisticated and comprehensive tests.

Handling Alerts and Popups

To handle JavaScript dialogs like alert, prompt, and confirm, Playwright provides straightforward APIs:

page.on("dialog", async (dialog) => {
    console.log(dialog.message())
    await dialog.accept()
})

Taking Screenshots and Videos

You can capture screenshots and even record videos of your tests:

// Taking Screenshot
await page.screenshot({ path: "screenshot.png" })

// Recording Video
const context = await browser.newContext({ recordVideo: { dir: "./videos/" } })
const page = await context.newPage()

Network Interception

Intercept network requests to test different API responses:

await page.route("**/api/*", (route) => {
    route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ message: "Mocked response" }),
    })
})

Conclusion

Automated browser testing can be a game-changer for your development workflow, and Playwright makes this task accessible and efficient. From its cross-browser support to its auto-wait features, Playwright is designed to make your testing experience as smooth as possible. Whether you’re just getting started or looking to enhance your existing tests, Playwright offers a myriad of features to ensure robust, reliable test automation.

So why wait? Get started with Playwright today and bring your browser testing to the next level.

Report bugs like it's 2024
Bug reports has looked the same since forever. You try to jam as much detail as possible to avoid the dreaded "can't reproduce". It's time to fix that. Whitespace captures every possible detail automatically and puts it all in a neat little package you can share as link.

Read more

Getting Started with Puppeteer in Node.js

Modern web development often requires testing and automating various web applications and processes. Read more

Published 3 min read
Getting Started with Playwright in PHP

In the fast-paced world of web development, testing is essential to ensure the stability and functionality of applications. Read more

Published 3 min read
Getting Started with Playwright in Python

In the realm of web application development, ensuring that your application works flawlessly across different browsers is no small feat. Read more

Published 3 min read
Getting Started with Playwright in C#

In the fast-evolving world of web development, you need reliable tools for your end-to-end testing to ensure your applications run smoothly across different browsers and environments. Read more

Published 3 min read
Getting Started with Playwright in Java

Modern web development can sometimes feel like a whirlwind of continuous updates and new tools. Read more

Published 5 min read
Getting Started with Playwright in Node.js

In the world of web development, automated browser testing can be a complex yet essential task. Read more

Published 3 min read
Getting started with Selenium in C#

In today's fast-paced development environment, ensuring that web applications are functioning correctly is crucial. Read more

Published 4 min read
Getting Started with Selenium in PHP

Imagine this: you've just finished building a shiny new PHP application that you’re incredibly proud of. Read more

Published 3 min read
Getting Started with Selenium in Python

Ever found yourself in a situation where you need to automate tedious web tasks but don't know where to start? Perhaps you're frequently logging into a website, scraping data for a project, or testing web applications manually. Read more

Published 3 min read
Getting Started with Selenium in JavaScript

The rapid pace of web development brings along a host of challenges, one of which is ensuring that web applications behave as expected across different browsers and devices. Read more

Published 3 min read
One-click bug reports straight from your browser
Built and hosted in EU 🇪🇺