Playwright Testing 1 - installation
Installing Playwright
Playwright (and Cypress) are a bit more complicated to set up when compared to unit tests. One reason for this is that they require at least one server up to run the tests against. (Two servers, if you have an API server that is part of your app.) Another is that it runs the tests multiple times on different browsers (which may need to be installed.)
Playwright comes with a sort of installer. Much like Create React App, it generates enough testing code for you to get started and it also installs the browsers you need for headless (non headless) testing. The command is as follows, and you can run it in the root of your project directory, or you can start a new project to test a remote server. (In a monorepo, you can put the e2e tests in their own directory, if you wish, and separate them from the frontend server and api server.) See here: https://playwright.dev/docs/intro#installing-playwright
npm init playwright@latest
On installation, it will print out a message that will contain a few commands to get started. One of them is
npx playwright test
This will run the example tests against a remote demo server that the Playwright team maintains.
It should all work, and getting this basic setup is quick and painless.
Testing your own project
Next, you can try to test your own project.
First, start the dev server. Maybe your project uses npm start
to start a server on PORT 3000. Then you can write tests that navigate to http://localhost:3000
and interact with the page and then expect certain changes on user interaction, for example, button clicks.
test('button text changes on click', async ({ page }) => {
// navigate to page
await page.goto('http://localhost:3000');
// click button
await page.getByRole('button', { name: 'Click me' }).click();
// wait for button text to change
await expect(page.getByRole('button', { name: 'Clicked!' })).toBeVisible();;
});
The examples that were generated on installation or the documentation at https://playwright.dev/docs/writing-tests
can help you with getting started.