Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for My First Playwright Tests
Corina: Web for Everyone
Corina: Web for Everyone

Posted on • Edited on

     

My First Playwright Tests

A blog series about playing and writing in 🎭


I'm a developer learning about web accessibility, and I would like to add Playwright to my toolset for testing web accessibility compliance.

So far, I've found that it offers straightforward syntax and excellent automation capabilities. Plus, the best documentation in the universe. (Yes, I believe aliens would use Playwright for some of their testing needs!)

This post is about the first three tests I wrote and how I applied them to my portfolio site.


Getting Started with 🎭

First, to get started (i.e., installation, how to run tests, etc.), I highly recommend Debbie O’Brien’s series of articles published on dev.to. I've included the link below in the Resources section.

Once installed, Playwright comes with example tests to help you get started. I adapted some of these examples to create three tests specifically for my portfolio site:

✔️ To navigate to the home page of my portfolio site and check if the title matches an expected string.
✔️ To check for the visibility of the home page’s heading.
✔️ To check whether the “My Projects” link is functional.

Note: My site is still in construction, so expect to find errors beyond those tested here.

Here are all three of the tests:

import{test,expect}from'@playwright/test';test('has title',async({page})=>{awaitpage.goto('https://corinamurg.netlify.app/');awaitexpect(page).toHaveTitle(/Corina's Portfolio/);});test('has heading',async({page})=>{awaitpage.goto('https://mywebsite.com/');awaitexpect(page.getByRole('heading',{name:'HELLO, I’m CORINA!'})).toBeVisible();});test('My Projects link',async({page})=>{awaitpage.goto('https://corinamurg.netlify.app/');awaitpage.getByRole('link',{name:'My Projects'}).click();});
Enter fullscreen modeExit fullscreen mode

Understanding the Code for Test 1

Let's break the code down into smaller steps and analyze them!

Step 1: We have to import two functions from Playwright:test andexpect:

import{test,expect}from'@playwright/test';
Enter fullscreen modeExit fullscreen mode
  • thetest function is used to define an individual test.
  • expect is an assertion function that checks whether a certain condition is met.

Heads up: the termassertion frequently appears in Playwright. An assertion is a check within a test that verifies whether certain conditions are met. So it basically evaluates a specific condition and passes or fails the test based on the result.

Step 2: Define a test namedhas title

test('has title',async({page})=>{
Enter fullscreen modeExit fullscreen mode

Step 3: Navigate to my website

awaitpage.goto('https://corinamurg.netlify.app/');
Enter fullscreen modeExit fullscreen mode

Step 4: Add an assertion to check if the webpage's title contains the text "Corina's Portfolio"

awaitexpect(page).toHaveTitle(/Corina's Portfolio/);
Enter fullscreen modeExit fullscreen mode

A few important notes

  • thetest function requires a string as its first argument to name the test, and a function as its second argument. This function is where you write the actual test code. It’s an asynchronous function that receives apage object.
  • a test interacts with web pages through thispage object, which is an instance of thePage class. ThePage class provides a wide range of methods that allows us to simulate any possible user interactions and scenario. For example, use.goto() to navigate to URLs,page.click() orpage.fill() to interact with elements,page.locator() to query the DOM. I highly recommend checking outthe documentation on the Page class and its methods.
  • await is necessary because Playwright operates asynchronously. It performs actions in a browser environment that requires waiting for the actions to complete before moving to the next step.

Now let’s look briefly at the other two tests as well.

Test 2

// Define a test named 'has heading'test('has heading',async({page})=>{awaitpage.goto('https://corinamurg.netlify.app/')// Expect page to have a heading with name of 'HELLO, I’m CORINA!'awaitexpect(page.getByRole('heading',{name:'HELLO, I’m CORINA!'})).toBeVisible();});
Enter fullscreen modeExit fullscreen mode

Test 3

// Define a test named 'My Projects link'test('My Projects link',async({page})=>{awaitpage.goto('https://corinamurg.netlify.app/')// simulate a user clicking on the 'My Projects' linkawaitpage.getByRole('link',{name:'My Projects'}).click();});
Enter fullscreen modeExit fullscreen mode

Playing with Errors

As an experiment, I modified thehas title test with a different expected title, which, as anticipated, led to a failed test due to the mismatch.

Here is the (quite long) error log:

Error:Timedout5000mswaitingforexpect(locator).toHaveTitle(expected)Locator:locator(':root')Expectedpattern:/Mysite/Receivedstring:"Corina's Portfolio"Calllog:-expect.toHaveTitlewithtimeout5000ms-waitingforlocator(':root')-locatorresolvedto<htmllang="en"></html>-unexpectedvalue"Corina's Portfolio"-locatorresolvedto<htmllang="en"></html>-unexpectedvalue"Corina's Portfolio"-locatorresolvedto<htmllang="en"></html>-unexpectedvalue"Corina's Portfolio"-locatorresolvedto<htmllang="en"></html>-unexpectedvalue"Corina's Portfolio"-locatorresolvedto<htmllang="en"></html>-unexpectedvalue"Corina's Portfolio"-locatorresolvedto<htmllang="en"></html>-unexpectedvalue"Corina's Portfolio- locator resolved to <html lang="en">…</html> - unexpected value"Corina's Portfolio" - locator resolved to <html lang="en">…</html> - unexpected value "Corina'sPortfolio"
Enter fullscreen modeExit fullscreen mode

Theexpect function was waiting for the page title to match "My site", but instead found "Corina's Portfolio". This mismatch between expected and actual results caused the test to fail.

The repeated lines like-unexpected value 'Corina's Portfolio' and-locator resolved to <html lang='en'>…</html> show thatPlaywright was continually checking the page title within the specified timeout period (5000ms). Each line likely represents an attempt to recheck the title against the expected value. Of course, it consistently found a value that did not match the expected pattern.

Conclusion 😊

I'm thrilled that my first three tests were successful! To create these tests I adapted the example tests that Playwright adds at installation. In the next post I will talk about another test that I created with just a click of a button! Seriously!

Resources

Debbie O’Brien’s Playwright Series on dev.to

Playwright Documentation

Image credit: Photo byAlex Kondratiev

Description: The image shows a hand pouring a blue liquid from a glass test tube into a flask with red liquid, and another hand pouring a green liquid into the flask. The background is plain white.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

👩‍💻 Accessibility | E2E Testing
  • Location
    USA
  • Education
    freeCodeCamp
  • Pronouns
    she/her
  • Work
    Gridiron Survivor
  • Joined

More fromCorina: Web for Everyone

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp