krishworkstech.com

Writing Tests in PlayWright

Introduction

Playwright tests are straightforward: they execute actions and verify the state against anticipated outcomes.

Playwright inherently waits for actionability checks to succeed prior to executing each action. There is no requirement to incorporate manual waits or manage race conditions. The assertions in Playwright are crafted to articulate expectations that will ultimately be fulfilled, thereby removing unreliable timeouts and race-related checks.

coverimage 2 - part 5

How to write the first test

Examine the subsequent example to understand the process of writing a test.

Test File Path : tests/example.spec.ts   

				
					import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
  await page.goto('https://playwright.dev/');
  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/Playwright/);
});
test('get started link', async ({ page }) => {
  await page.goto('https://playwright.dev/');
  // Click the get started link.
  await page.getByRole('link', { name: 'Get started' }).click();
  // Expects page to have a heading with the name of Installation.
  await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
});

				
			

note

Add // @ts-check at the start of each test file when using JavaScript in VS Code to get automatic type checking.

How to perform actions

Navigation

The majority of tests commence by accessing a specific URL.

 

Subsequently, the test engages with the elements present on the page.

 

await page.goto(‘https://playwright.dev/‘);

 

The playwright pauses until the page has fully loaded before proceeding. Discover additional information regarding the options available for page.goto().

Interactions

Initiating actions begins with identifying elements. Playwright utilizes the Locators API for this purpose. Locators provide a method to locate element(s) on the page at any given time. Discover more about the various types of locators that are offered.

 

Playwright ensures that the element is ready for interaction before executing the action, eliminating the need for you to wait for its availability.

				
					// Create a locator.
const getStarted = page.getByRole('link', { name: 'Get started' });

// Click it.
await getStarted.click();

				
			

In most cases, it’ll be written in one line:

				
					await page.getByRole('link', { name: 'Get started' }).click();
				
			

Basic actions

Here are the most commonly used Playwright actions. To view the full list, please refer to the Locator API section.

Action

Description

locator.check()

Check the input checkbox

locator.click()

Click the element

locator.uncheck()

Uncheck the input checkbox

locator.hover()

Hover mouse over the element

locator.fill()

Fill the form field, input text

locator.focus()

Focus the element

locator.press()

Press single key

locator.setInputFiles()

Pick files to upload

locator.selectOption()

Select option in the drop down

How to use assertions

Playwright provides test assertions through the expect function. To create an assertion, invoke expect(value) and select a matcher that aligns with your expectation.

Playwright also offers asynchronous matchers that pause until the anticipated condition is satisfied. Utilizing these matchers ensures that tests are stable and robust. For instance, the following code waits for the page to have a title that includes “Playwright”:

				
					await expect(page).toHaveTitle(/Playwright/);
				
			

Here is a list of the most widely used async assertions. To view the full list, please refer to the assertions guide:

Action

Description

expect(locator).toBeChecked()

Checkbox is checked

expect(locator).toBeEnabled()

Control is enabled

expect(locator).toBeVisible()

Element is visible

expect(locator).toContainText()

Element contains text

expect(locator).toHaveAttribute()

Element has attribute

expect(locator).toHaveCount()

List of elements has given length

expect(locator).toHaveText()

Element matches text

expect(locator).toHaveValue()

Input element has value

expect(page).toHaveTitle()

Page has title

expect(page).toHaveURL()

Page has URL

Playwright offers generic matchers such as toEqual, toContain, and toBeTruthy, which can be utilized to assert various conditions. These assertions do not require the await keyword since they execute immediate synchronous checks on values that are already available.

				
					expect(success).toBeTruthy();
				
			

How tests run in isolation

Playwright Test operates on the principle of test fixtures, including the built-in page fixture that is provided to your test. Each test is conducted in isolation thanks to the Browser Context, which functions like a completely new browser profile. This ensures that every test has a clean environment, even if several tests are executed within the same browser.


File Path : tests/example.spec.ts

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

test('example test', async ({ page }) => {
  // "page" belongs to an isolated BrowserContext, created for this specific test.
});

test('another test', async ({ page }) => {
  // "page" in this second test is completely isolated from the first test.
});

				
			

How to use test hooks

You can utilize different test hooks like test.describe to define a group of tests, along with test.beforeEach and test.afterEach, which run before and after each individual test. Additional hooks include test.beforeAll and test.afterAll, which are executed a single time per worker before and after all tests.


File Path:  tests/example.spec.ts

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

test.describe('navigation', () => {
  test.beforeEach(async ({ page }) => {
    // Go to the starting url before each test.
    await page.goto('https://playwright.dev/');
  });

  test('main navigation', async ({ page }) => {
    // Assertions use the expect API.
    await expect(page).toHaveURL('https://playwright.dev/');
  });
});

				
			

Playwright Essentials: A Step-by-Step Journey into Test Automation

cover - part 9

Part 01: Master Playwright Testing – Framework from Scratch Guide

cover - part 10

Part 02: How to install Playwright

cover - part 11

Part 03: Basic Playwright Test Structure

cover - part 13 (1)

Part 04: Importance of Playwright configuration file and its details to run the tests

cover - part 17

Part 05: Writing Tests in PlayWright

cover - part 19

Part 06: Playwright Actions Illustrated

Scroll to Top
  • Schematic design
  • PCB and schematic source files
  • Assembling drawing files
  • Providing prototype/sample and production PCB service
  • Testing and validation of designed hardware
  • HIPAA
  • Azure Key
  • Management
  • ES, Checksum,
  • MD5sum
  • AWS
  • Azure
  • GCP
  • DigitalOcean
  • Kotlin
  • Python
  • Tensorflow
  • Computer Vision
  • ECG
  • SPO2
  • Heart Rate
  • Glucometer
  • Blood Pressure
  • UX UI Process
  • Figma and FigJam
  • Adobe Suite
  • Selenium Java
  • Postman
  • Swagger
  • Jmeter
  • SQL
  • Java Scripter
  • Test ng
  • Extents Reports
  • Flutter
  • Java
  • Kotlin
  • Swift
  • Dart
  • React JS
  • Python
  • NodeJS
  • Django
  • HTML, CSS, JS
RDBMS
  • PostgreSQL
  • Oracle
  • MySQL
  • MariaDB
No SQL Based
  • MongoDB
  • GCP
  • FirestoreDB
  • DynamoDB
  • Azure
  • CosmosDB
  • AWS