Testing With Playwright: A Tutorial Guide With Examples
Published: 2023-10-25 22:52:13

by [Emmanuel Uchenna](https://blog.openreplay.com/authors/emmanuel-uchenna)

<blockquote><em>In modern software development, particularly with agile methodology, software testing is a paramount process in the [Software Development Lifecycle (SDLC)](https://aws.amazon.com/what-is/sdlc/). It is the practice of analyzing and verifying that a software application performs as intended, and this article will focus on Playwright, the testing tool, and see how to apply it and why.</em></blockquote>

Software testing ensures that organizations deliver high-quality software products. As a software developer or a software tester, software testing is crucial because it ensures that the software works properly, enables you to identify and fix bugs, and improves the overall quality of your application. Testers ensure that the program does what it is supposed to do by employing various testing techniques and types.
Software testers use various test automation tools to carry out these tests. Some of these automation testing tools include [Playwright](https://playwright.dev/), [WebdriverIO](https://blog.openreplay.com/end-to-end-testing--unleash-the-power-of-webdriverio), [Puppeteer](https://blog.openreplay.com/playwright-vs-puppeteer--which-to-choose/), [Cypress](https://blog.openreplay.com/end-to-end-testing-with-cypress/), etc.
[Playwright](https://playwright.dev/) is a Node.js test automation framework developed by Microsoft in 2020. It offers a high-level API for easily automating modern web apps, and it supports all modern web browsers. It automates web tests by simulating user interactions such as clicks, scrolls, and keyboard inputs and performing complex actions such as filling out forms and navigating between pages. Playwright also has built-in support for waiting for specific page elements to load before proceeding with the automated test, which helps to make tests more stable and less prone to flakiness. Automated testing finds more relevance, especially in Continuous Integration workflows, as it ensures the application works as expected.
In this article, you will learn how to start writing your tests using Playwright on [Visual Studio Code](https://code.visualstudio.com/download).
## Main features of Playwright
The Playwright framework supports multiple programming languages. This allows for greater flexibility while working with the framework. The supported languages include NodeJS, Python, C#, JavaScript, TypeScript, and Java.
As to browsers, one of the top features that set Playwright apart from its test automation framework counterpart is its [support for different browsers](https://playwright.dev/docs/browsers). These browsers include all Chromium-based rendering engines: Google Chrome (Chrome 66 and above), Firefox (76 and above), and all WebKit-based rendering engines such as Safari. As of when I wrote this article, Playwright does not support [IE 11](https://github.com/microsoft/playwright/issues/647).
The simple Playwright API lets you automate all major web browsers without the hassle of configuring tests for specific browsers. Here are a few reasons why you should consider using Playwright for your test automation:
1. **Auto-Waits**: Playwright [auto-waiting](https://playwright.dev/docs/actionability) feature allows you, as a tester, to perform some checks on elements before carrying out actions to prevent flakiness. This ensures that your tests run smoothly even when dynamic elements are loading on the page.
2. **Cross-Browser Testing**: Playwright allows you to effortlessly test your application across multiple browsers, such as Chrome, Firefox, Internet Explorer, and Safari, ensuring consistent behavior and appearance.
3. [**Tracing and Debugging**](https://playwright.dev/docs/trace-viewer#viewing-the-trace): Playwright provides detailed traces of your test executions, allowing you to trace every step and uncover the reason of failed tests in form of [traces](https://playwright.dev/docs/trace-viewer) using its [trace viewer](https://playwright.dev/docs/trace-viewer). This allows you to visually review what transpired during the tests. It's like having a time-traveling assistant that lets you see exactly what happened, step by step, helping you diagnose issues and understand the test execution flow. See the following video:
[![React Query](https://img.youtube.com/vi/lfxjs--9ZQs/0.jpg)](https://www.youtube.com/watch?v=lfxjs--9ZQs)
4. **Parallel Testing**: [Parallel testing](https://webdriver.io/docs/organizingsuites/) entails executing multiple tests at the same time concurrently. This will help you obtain feedback much more quickly, which is critical when working with large and complex software applications. WebdriverIO, as an automation test framework, enables you to carry out [parallel tests](https://webdriver.io/docs/organizingsuites/). Learn more about parallel testing on the official WebdriverIO [documentation](https://webdriver.io/docs/organizingsuites/).
5. **Speed and Reliability**: Speed and reliability are like the twin pillars of Playwright. It's designed for fast and dependable test automation. With its optimized engine, Playwright executes your tests swiftly.
6. **Headless Execution**: For a speedy test, run your tests using the headless browser mode in Playwright. A headless browser is essentially a browser without a UI. With headless execution, you can run tests without a visible browser interface, saving resources and allowing seamless integration into your CI/CD pipelines. If you want the UI mode, Playwright also has support for that with the `--ui` flag, and you are seconds away from [experiencing the UI mode](https://playwright.dev/docs/running-tests).
  
7. [**Video Recording**](https://playwright.dev/docs/videos): Playwright introduces a unique video recording feature that captures test runs, allowing replay for analysis. It offers multiple recording options, catering to various needs.
## Why You Should Use Playwright
Beyond its aforementioned features, Playwright's popularity has significantly grown, resulting in widespread adoption within the industry. Consider the following indicators:

* GitHub Stars: 53k+ ([August, 2023](https://github.com/microsoft/playwright))

* Weekly Downloads: Over 1.5M ([August, 2023](https://www.npmjs.com/package/playwright))

* Forks: 2.9k ([August, 2023](https://github.com/microsoft/playwright))

* License: [Apache License 2.0](https://github.com/microsoft/playwright/blob/main/LICENSE)

* Supportive Community: Active and responsive [community](https://playwright.dev/community/welcome)

* Extensive Documentation: [Yes](https://playwright.dev/docs/intro)

* Lightweight: Bundle size of 24.2 kB (v1.36.2)
The following chart illustrates the download trends of [**Playwright**](https://playwright.dev/ "Playwright") over the past two years.
[![Playwright download trend in 2years](https://blog.openreplay.com/images/testing-with-playwright/images/z5iPekZ.png)](https://npmtrends.com/playwright)

## Setting Up Playwright in Your Project: Code Examples and Walk-Throughs
Before proceeding, make sure to meet the following requirements:
1. Have the latest version of [NodeJS installed](https://nodejs.org/en/download) on your local machine.
2. **Confirm Installation**: Verify a successful Node.js installation by running `node -v` in your terminal. You should observe output similar to the following: `v18.15.0`
3. **Confirm NPM installation**: Verify a successful NPM installation by executing `npm -v` in your terminal. Node.js installation includes NPM.
4. If you're not already using it, download and [install VSCode](https://code.visualstudio.com/download), a popular code editor.
5. Next, you will need to install the [Playwright VSCode extension](https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright) to make testing streamlined.
![Playwright Test for VSCode](https://blog.openreplay.com/images/testing-with-playwright/images/u3000Og.png)
6. Install Playwright:
 Launch VSCode and use `CTRL + SHIFT + P` to access the command palette.
 Type `Install Playwright` and hit `Enter`
![Install Playwright](https://blog.openreplay.com/images/testing-with-playwright/images/G4RH36A.png)
7. Upon successful installation, your terminal should confirm Playwright's installation:
![Successful installation—Playwright](https://blog.openreplay.com/images/testing-with-playwright/images/fhjylNv.png)
8. This installation includes Chrome, Firefox, and WebKit browsers, along with sample test files located in the `tests` folder.
In the subsequent steps, we will modify the default test file at `tests/example.spec.ts` to conduct tests on the OpenReplay website.

<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>

## Examples Tests with Playwright

Below is a sample test that accomplishes the following:

1. Navigate to the OpenReplay website and test that the title contains the string "OpenReplay"

2. Click on "Get Started" on the navigation bar and verify that the URL contains the string "get-started".

```javascript
// tests/example.spec.ts
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
 await page.goto('https://openreplay.com/');
 // Expect a title "to contain" a substring => OpenReplay
 await expect(page).toHaveTitle(/OpenReplay/);
});
test('get started link', async ({ page }) => {
 await page.goto('https://openreplay.com/');
 // Click the "Get Started" button.
 await page.getByRole('button', { name: 'Get Started' }).click();
 // Expects the URL to contain "get-started"
 await expect(page).toHaveURL(/.*get-started/);
});
```

![Test result](https://blog.openreplay.com/images/testing-with-playwright/images/qSTZ0xi.png)
### Writing Your Playwright Test: Code Snippet Examples

```javascript
const playwright = require('playwright');
(async () => {
 for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit]) {
  const browser = await browserType.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://openreplay.com');
  await page.screenshot({ path: `example-${browserType.name()}.png` });
  await browser.close();
 }
})();
```

In this illustrative code snippet, Playwright navigates to [https://openreplay.com](https://openreplay.com) using Chromium, Firefox, and WebKit browsers, capturing three screenshots named after the respective browsers.
![example-firefox.png](https://blog.openreplay.com/images/testing-with-playwright/images/ZXDBzAG.png)
**Note:** You may use the [Playwright Playground](https://try.playwright.tech/) to play around with these tests.
## Integrating Playwright with Other Test Frameworks
Playwright can be integrated with [other third-party test frameworks](https://www.cuketest.com/playwright/docs/test-runners/) that are based on the same protocol as Playwright. For example, frameworks such as [Jest](https://jestjs.io/), [Mocha](https://mochajs.org/), [AVA](https://avajs.dev/), and [Jasmine](https://jasmine.github.io/).
Achieving this integration requires just a few lines of code.
### Jest / Jasmine + Playwright

```javascript
const {chromium} = require('playwright');
const expect = require('expect');
let browser;
let page;
beforeAll(async () => {
 browser = await chromium.launch();
});
afterAll(async () => {
 await browser.close();
});
beforeEach(async () => {
 page = await browser.newPage();
});
afterEach(async () => {
 await page.close();
});
it('should work', async () => {
 await page.goto('https://openreplay.com');
 expect(await page.title()).toBe('OpenReplay: Open-Source Session Replay & Analytics');
});
```

### AVA + Playwright

```javascript
const {chromium} = require('playwright');
const test = require('ava').default;
const browserPromise = chromium.launch();
async function pageMacro(t, callback) {
 const browser = await browserPromise;
 const page = await browser.newPage();
 try {
  await callback(t, page);
 } finally {
  await page.close();
 }
}
test('should work', pageMacro, async (t, page) => {
 await page.goto('https://openreplay.com');
 t.is(await page.title(), 'OpenReplay: Open-Source Session Replay & Analytics');
});
```

### Mocha + Playwright

```javascript
const {chromium} = require('playwright');
const assert = require('assert');
let browser;
before(async() => {
 browser = await chromium.launch();
});
after(async () => {
 await browser.close();
});
let page;
beforeEach(async() => {
 page = await browser.newPage();
});
afterEach(async () => {
 await page.close();
});
it('should work', async () => {
 await page.goto('https://openreplay.com');
 assert.equal(await page.title(), 'OpenReplay: Open-Source Session Replay & Analytics');
});
```

## Conclusion
In this article, I started with the importance of testing software products as a software developer and tester and why it is an indispensable step in the SDLC. I walked you through the installation and setup of Playwright - a test automation framework.
Finally, you learned how to carry out basic tests with Playwright.
In a previous article, I wrote about how to carry out [E2E tests using WebdriverIO](https://blog.openreplay.com/end-to-end-testing--unleash-the-power-of-webdriverio/) test framework.
Also, check out how [OpenReplay](https://openreplay.com/get-started.html) can help you understand and surface issues in your web application. [OpenReplay](https://openreplay.com/get-started.html) helps you spend less time debugging and empowers you to create [delightful web experiences](https://openreplay.com/product.html).