Articles

Getting Started with Playwright in Node.js

2024-08-11·3 min read
Photo by Duncan Meyer on Unsplash

In the world of web development, automated browser testing can be a complex yet essential task. Traditional testing frameworks often require heavy configurations and can be time-consuming. Enter Playwright, a powerful tool developed by Microsoft to simplify and streamline browser automation. In this guide, we'll delve into the basics of getting started with Playwright in a Node.js environment, making your journey into automated testing smoother and more effective.

Why Playwright?

Before jumping into the details, let's understand why Playwright stands out in the crowded field of testing libraries. Playwright provides:

  1. Cross-browser support: It supports Chromium, Firefox, and WebKit.
  2. Consistency: Ensures your tests run seamlessly across different browsers.
  3. Flexible and comprehensive API: Offers tools for a wide range of actions like interactions, navigations, and assertions.
  4. Headless and headed execution: You can run tests in the background or watch them in action.
  5. Built-in support for modern web features: Easily handle situations involving frames, workers, and more.

Prerequisites

To get started with Playwright, you should have the following tools installed:

  1. Node.js: Ensure you have Node.js installed on your system. You can download it from Node.js.
  2. NPM: Node Package Manager, which comes bundled with Node.js.

Setting Up Your Project

First, let's create a new Node.js project.

Step 1: Initialize your Node.js project

Open your terminal and run the following commands:

mkdir playwright-demo
cd playwright-demo
npm init -y

This will create a new directory named playwright-demo and initialize it as a Node.js project.

Step 2: Install Playwright

Now, install Playwright by running:

npm install --save-dev playwright

Step 3: Write Your First Test

Create a new file named example.spec.js in the root of your project:

touch example.spec.js

Open example.spec.js in your favorite editor and add the following code:

const { chromium } = require("playwright")
;(async () => {
    // Launch a browser instance
    const browser = await chromium.launch()
    const context = await browser.newContext()
    const page = await context.newPage()

    // Navigate to a webpage
    await page.goto("https://example.com")

    // Take a screenshot
    await page.screenshot({ path: "example.png" })

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

Step 4: Running the Test

Run your test through Node.js:

node example.spec.js

If everything is set up correctly, this script will launch a Chromium browser, navigate to https://example.com, take a screenshot, and close the browser. You'll find the screenshot saved as example.png in your project directory.

Photo by Sebastian Bill on Unsplash

Understanding the Basics

Launching a Browser

Playwright supports three browser engines: Chromium, Firefox, and WebKit. You can launch any of these by importing the respective module:

const { chromium, firefox, webkit } = require("playwright")

To launch a Chromium browser:

const browser = await chromium.launch()

If you want to see the browser in action, pass { headless: false }:

const browser = await chromium.launch({ headless: false })

Creating Browser Contexts

A browser context represents an isolated session within a browser. You can use contexts to simulate different environments in different test scenarios:

const context = await browser.newContext()

Opening a New Page

Create a new page within your context:

const page = await context.newPage()

To navigate to a specific webpage, use:

await page.goto("https://example.com")

Taking Screenshots

To take a screenshot, simply call:

await page.screenshot({ path: "example.png" })

Closing the Browser

After your tasks are complete, close the browser to free up resources:

await browser.close()

Advanced Features

Playwright offers several advanced features that make it a robust tool for browser automation.

Emulating Devices

You can emulate different devices to test mobile responsiveness:

const iPhone = playwright.devices["iPhone 11"]
const context = await browser.newContext({
    ...iPhone,
    locale: "en-US",
    geolocation: { latitude: 37.7749, longitude: -122.4194 },
})

Handling Frames

For pages with iframes, use the frame method to switch between frames:

const frame = await page.frame({
    name: "frameName",
})
await frame.click("button")

Capturing Logs

To capture console logs during your tests:

page.on("console", (msg) => console.log(msg.text()))
await page.goto("https://example.com")

Network Interception

You can intercept and mock network requests:

await page.route("**/*", (route) => {
    if (route.request().url().includes("example")) {
        route.fulfill({
            status: 200,
            contentType: "application/json",
            body: JSON.stringify({ foo: "bar" }),
        })
    } else {
        route.continue()
    }
})

Conclusion

Playwright is a cutting-edge tool that brings simplicity and robustness to browser automation and testing. With its straightforward API, cross-browser support, and advanced capabilities, it empowers developers to create high-quality web applications with ease. By following this guide, you should now have a foundational understanding of how to get started with Playwright in a Node.js environment. Dive deeper into the official documentation to explore more functionalities and take your testing to the next level. Happy testing!

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 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 JavaScript

Development and testing can often feel like taming a herd of wild animals. Read more

Published 4 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
Getting Started with Selenium in Java

Developers are often on the hunt for efficient ways to automate web browser interactions for testing purposes. Read more

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