Functions and Selectors in Playwright: A Step-by-Step Tutorial

  • Learning Hub
  • Functions and Selectors in Playwright: A Step-by-Step Tutorial

OVERVIEW

Playwright is one of the most promising automation testing frameworks in the market today, with its unique features. The Playwright has an array of features that help to write tests more conveniently. The Functions and Selectors in the Playwright automation framework are the building blocks to creating a highly-customized automated test script.

This Playwright testing tutorial will help you learn how to use Functions and Selectors extensively to perform automated browser testing with Playwright. You will also learn about the importance of Playwright concepts like browserContext and a newPage and their usage.

Subscribe to LambdaTest YouTube Channel to tune into more tutorials around automation testing with Playwright or other automation testing frameworks such as Selenium, Cypress, Puppeteer, etc.

...

Table of Contents

Test Block in Playwright

To launch a browser, you need to know a few concepts. One such concept is Test Block. You might know about JavaScript testing frameworks like WebdriverIO and Protractor, and test runners such as Jasmine and Mocha. If you consider Jasmine or Mocha, you will get a description block that consists of eight blocks.

Test Block in Playwright

Similarly, in Playwright, you have an inbuilt test runner called “playwright test runner.”

Let's take a basic test scenario of a demo page on LambdaTest Selenium Playground to validate and try these Playwright inputs.

  • The first step is to use the Test Block. The Playwright supports ‘async and await’ to handle the promises. Hence, you don’t have to write “.then()” and “.catch()” as it’s done in JavaScript.
  • Next, you need to import the test.
  • After importing the test, the next step is to launch the browser.

As a whole, the code for the test block, import, and launching of the browser will look like this -


test(“Login test demo”, async () =>
import {chromium, test} from@playwright/test”
           const browser = await chromium.launch();
           const context = await browser.newContext();
           const page = await context.newPage();

Kudos, you managed to launch the Chromium browser. Playwright supports multiple contexts and pages. It ensures that one context does not share its cookies or cache with another.

How to launch a Chromium browser with Playwright?

In the previous chapter of the Playwright testing tutorial, we learned how to install Playwright and set it up on VS Code.

Post installation, you get a test folder. Under “playwright.config.ts” you need to delete the entire code except for the default code. The code consists of import statements with “PlaywrightTestConfig.” Next, you will need to export the import statement as a config.

Default code:



Import type { PlaywrightTestConfig } from@playwright/test’;
const config: PlaywrightTestConfig = { };
export default config;

This is the default code. Hence, it’s called global configuration. Once you use the default code, it takes care of all the test codes in the future. Next, you need to create a new file called “login.test.ts.”

...

How to write a login script using Playwright?

We will use the LambdaTest eCommerce Playground (demo account).

Test Scenario:

  • Go to My account and enter your credentials to log in.
  • Under My account, right-click and choose Inspect.
  •  right-click and choose Inspect

    When we open the inspector, we need to locate “My account” under elements. For example, if the term “My account” exists in three different places, we cannot use the direct locator test.

     My account under elements

    Instead, we need to go to the official Playwright website “playwright.dev”. Go to the Docs section. You can locate “Guides” under which there will be “Selectors.” Playwright has a wide variety of selectors to locate elements on the web page.

     
  • Next, we will right-click the Login text and open the Inspector. Under elements, we need to locate the word “login.” Here, we see only one term. Hence we do not consider the XPath locator but instead, use the direct locator.

import { chromium, test } from "@playwright/test"
 
 test("Login test demo", async () => {
  
     const browser = await chromium.launch({
         headless: false
     });
     const context = await browser.newContext();
     const page = await context.newPage();
  
     await page.goto("https://ecommerce-playground.lambdatest.io/")
     await page.hover("//a[@data-toggle='dropdown']//span[contains(.,'My account')]")
     // await page.click("text=Login")
     await page.click("'Login'")
 })
 

GitHub

How to execute the script using Playwright?

Let’s automate the login process to an e-commerce web application.

Test Scenario:

  • Go to the LambdaTest eCommerce Playground.
  • Click on the Login button.
  • Enter your E-Mail Address and Password and hit the Login button.

Execute the script in VS Code -

  • When we use VS Code, it is in either powershell or command prompt mode by default. However, it would be preferable to choose git bash as it is beneficial. In the VS Code, go to the config file that says “playwright.config file.”.
  • We will run the file that says “login.test.test”
  • login.test.test
  • Get back to the login test, and bring up the terminal using Ctrl+J.
  • Now type -
  • “npx playwright test”

  • The test runs in the terminal.
  • npx playwright test

    Playwright, by default, works in the headless mode. Hence we cannot see the browser in the taskbar.

  • To view the browser, we need to go back to the login script and add the term “headless: false.”
  • headless: false

    Eventually, we can see the browser and the launch of the website.

  • Go back to the LambdaTest eCommerce Playground, and enter your E-Mail Address and Password.
  • Next, we will inspect the email address and password. We can view the XPath as well as CSS. Under CSS, we have a unique CSS selector that shows the name and password.
  • CSS selector that shows the name and password

    Copy this unique name and password from CSS into the VS Code. The function that we use is the “fill.”.


    await page.fill(“input[name = ‘email’]”, “koushik350@gmail.com”)
    await page.fill(“input[name = ‘password’]”, “Pass123$”)
    

  • After inspecting the E-Mail and Password, we need to inspect “login.” Repeat the above process.

  • await page.click(“input[value=’login’]”)

  • To ensure that the page completely loads, we use the “waitForTimeout” function.

  • await page.waitForTimeout(5000)

When we execute the test in the terminal, it shows as a pass. We can conclude that we have successfully executed the test. Finally, on the LambdaTest eCommerce Playground, we will see the website's opening, followed by login and entering email and password. Bravo, the execution of the test is successful.

execute the test in the terminal Functions And Selectors

To sum up,

  • Use the “goto” function to navigate to a site.
  • Use the “hover” function to perform the mouse hover action.
  • Use the “click” function to click on any element.
  • Use the “fill” function to type and send test data.
  • Use the “waitForTimeout” function so that the page loads completely, resulting in the proper execution of a test. It is similar to “thread.sleep”.

Understanding newPage and browserContext in Playwright Testing

newPage in Playwright

A page in the context of a browser is a single tab or popup window. It can navigate URLs and interact with page content.

Here’s an example of how newPage works:

  • Open the LambdaTest eCommerce Playground.
  • Enter your login credentials, and you will be redirected to a page that says “My account.”
  • Open the same link in another tab. If your application supports assertion and cache, you will view the same page in the new tab. Likewise, if you log out in the first tab, the same repeats in the second tab (due to assertion and cache).
  • Demonstrate these steps in the VS Code by navigating to the login URL. Execute the test under the terminal. We can view the same page in the first and second tabs.

browserContext in Playwright

browserContext allows you to run multiple independent browser sessions. For instance, when a page calls for the opening of another page, such as using an open window call, a popup will appear in the browser context of the parent page. It may consist of multiple pages. In an application, we don't carry forward Cache and Assertion.

Here’s an example of creating a context:

  • Use the VS Code and enter the context code.
  • Execute the test in the terminal.
  • A new page opens, followed by the login.
  • Next, it brings a new browser rather than a tab, as we use “context” in the code. There’s no usage of assertion or cache as it is a newContext.
const newContext = await browser.newContext()

const newPage = await newContext.newPage();
await newPage.goto("https://ecommerce-playground.lambdatest.io/index.php?route=aaccount/login")

await newPage.waitForTimeout(5000);

If you are a developer or a tester looking to validate your Playwright test automation skills, you can go for Playwright 101 Certification from LambdaTest.

LambdaTest

Scale Playwright Testing with the LambdaTest Cloud

To scale your Playwright test execution, use LambdaTest, a cloud-based test execution and test orchestration platform consisting of an automation testing grid spanning over 3000 browsers and OS systems. LambdaTest enables you to

  • Execute the Playwright parallel testing over 50+ browsers and OS configurations and boost your release speed.
  • Debug Playwright tests using various logs, including network logs, command logs, and complete video recordings.
  • Execute Playwright tests 70% faster than any other testing cloud using LambdaTest's HyperExecute, the quickest end-to-end test orchestration cloud.
  • Create a unique dashboard and widgets to organize your test analytics easily and integrate with your CI/CD tools.

LambdaTest’s automation testing cloud also supports Selenium, Cypress, Puppeteer, and even app automation frameworks such as Appium, Espresso, XCUITest, etc.

...

Conclusion

You have learned about using Playwright functions and selectors. The primary focus was on concepts such as launching a browser, executing a test and context, and creating new pages. I hope this tutorial provides a clear understanding of Playwright functions and selectors.

Here’s a glimpse of how you can perform Playwright browser testing on the LambdaTest cloud grid.

Subscribe to the LambdaTest YouTube Channel and stay updated with the latest Playwright topics.

Frequently Asked Questions (FAQs)

What are the three types of selectors?

Three types of selectors are - Simple selectors (select elements based on name, id, and class), Combinator selectors (select elements based on a specific relationship between them) and Pseudo-class selectors (select elements based on a certain state).

How do I identify a selector?

A CSS ID selector uses the ID attribute of an HTML element to select one unique element on a page. To use an ID selector in CSS, you simply write a hashtag (#) followed by the element's ID. Then put the style properties you want to apply to the element in brackets.

What is the difference between an id and a selector?

The difference between id and selector is that “id” is unique on a page and can only apply to a single element, while the “class” selector can apply to multiple elements.

Did you find this page helpful?

Helpful

NotHelpful