Adding Playwright to a React web app.

Playwright is an automation testing framework for the web. Let’s add it to our React app. and demonstrate how to use it

Installation

  • Install Playwright
    yarn create playwright
    
  • You’ll be asked where to put your end-to-end tests, default is e2e so let’s stick with that
  • Next, you’ll be asked whether to add a GitHub actions workflow, default is N< but I want them, so selected Y
  • Now you’re asked whether to install Playwright browsers, default is Y so let’s stick with that
  • Now Playwright is downloaded and installed

Writing Tests

Within the folder we set for our tests, I used the default e2e we can start adding our *.spec.ts test files, for example here’s a simple example test just to check the title on my web app.

import { test, expect } from '@playwright/test';

test.beforeEach(async ({ page }) => {
  // obviously needs changing to your deployed web app, but
  // fine for local testing
  await page.goto('http://localhost:3000/');
});

test('Ensure title is as expected', async ({ page }) => {

  await expect(page).toHaveTitle(/My Web App/);
  await page.getByText('End Sat Dec 31 2022').click();
});

In the above we simple create a test and using playwright we automate testing of the web app.

Now to run this, as I’m using React, add to package.json the following to the scripts section

"playwright_test": "playwright test",
"playwright_report": "playwright show-report",

Now we can run yarn playwright_test to run the tests within e2e or whatever your test folder was named.