First Playwright Test

Cerosh Jacob
2 min readAug 26, 2023

--

Playwright is a modern, open-source, end-to-end automation framework for web browsers. It can be used to execute scripts against many types of browsers, including Chromium-based browsers such as Chrome, Edge, and Opera, Firefox, WebKit-based browsers such as Safari and Electron, and many others.

To write a Playwright test, you must import the required modules from the package, write a test function that takes a page object to interact with the browser, and then use the module to assert various aspects of the page.

  1. Install Playwright. You can do this by running the following command in your terminal:
npm init playwright@latest
  1. Create a new test file. You can do this by creating a new file with the .spec.ts extension.
  2. Import the test and expect modules from the @playwright/test package.
  3. Write a test function. The test function should have the test keyword as its first keyword. The function should also take a single parameter, which is a page object.
  4. Write assertions in the test function. The assertions should check for the expected behaviour of the page.
  5. Run the test. You can run the test by running the following command in your terminal:
npx playwright test

Here is an example of a playwright test:

import {test, expect} from '@playwright/test'
test("Test to check the title",async({page})=>{
await page.goto('<https://playwright.dev/>');
await expect(page).toHaveTitle(/Playwright/);
})

Playwright Test provides a test function for declaring tests and a expect function for writing assertions. Tests run in a fresh browser environment with a new page for each test.

The test function accepts two arguments: title: string and callBack: (args, testInfo: TestInfo). Since the callback function is asynchronous, all page interactions must be properly chained with await statements to ensure the page is in the expected state before proceeding. Omitting the await keyword in the first statement can result in the following error: Error: page.goto: Browser has been closed.

The playwright uses the expect function for making test assertions and a matcher that reflects the expectation. The isolated Page instance created for each test ensures that pages are isolated between tests. The toHaveTitle() matcher verifies that the page has the title given as the argument, which can be either an expected title as a string or a regular expression.

My recent publication compiled a comprehensive collection of 100 similar typescript programs. Each program not only elucidates essential Typescript concepts and expounds upon the significance of test automation but also provides practical guidance on its implementation using Playwright. This resource will undoubtedly be valuable if you look deeper into similar topics.

--

--

No responses yet