Please note that this article is a translation of the original. The original article can be Playwright Básico — Introdução à Automação de Testes Web.
Learn the basics of web testing automation with Playwright: from initial setup to navigating and interacting with page elements. Using JavaScript.
Introduction to Playwright
Playwright is a powerful web testing automation tool that supports multiple browsers, including Chrome, Firefox, and Safari. Its purpose is to enable developers and testers to automate interactions with web pages, such as clicks, form filling, and result validation. With an intuitive API and advanced features like visual evidence capture, mobile device support, and network emulation, Playwright makes the web testing automation process more efficient, reliable, and comprehensive. Playwright helps ensure the quality of web applications across different browsers and devices.
Playwright stands out from other web testing automation tools due to its key features and advantages. It provides native support for multiple browsers, allowing consistent test execution in Chrome, Firefox, and Safari. Additionally, Playwright has a unified API, easing the transition between different browsers and simplifying test maintenance. The ability to emulate mobile devices, detailed visual evidence capture, fast test execution, and support for complex scenarios like frames and pop-ups are further strengths of Playwright, making it a powerful and versatile choice for web testing automation.
Setting Up the Development Environment
Installing Playwright and its dependencies is the first step to harnessing the power of this web testing automation tool. The installation can be done through the npm or yarn package managers, along with its dependencies, such as the Chrome, Firefox, and Safari browsers.
Before diving into Playwright, it is essential to install Node.js. To quickly install Node.js, follow these steps:
- Visit the official Node.js website at https://nodejs.org.
- On the homepage, you’ll find different download options. We recommend choosing the LTS (Long Term Support) version for greater stability and long-term support.
- Select your operating system (Windows, macOS, or Linux) and click the corresponding download button.
- The Node.js installer download will begin. Wait until the download is complete.
- After the download, run the installer file.
- Follow the instructions of the installation wizard, accepting the terms of use and selecting default configuration options unless you have specific needs.
- Once the installation is complete, open a terminal or command prompt and type the following command to verify that Node.js has been installed correctly:
node -v
- In addition to Node.js, the installation also includes npm (Node Package Manager). Check the npm version with the following command:
npm -v
Step 1 — Create a New Project
Open a terminal or command prompt and navigate to the directory where you want to create the project. Then, run the following command to create a new Node.js project:
npm init -y
Step 2 — Playwright Installation
npm init playwright@latest
After installation, you will likely see the following directory structure:
playwright.config.ts
package.json
package-lock.json
tests/
example.spec.ts
tests-examples/
demo-todo-app.spec.ts
Delete the “tests-examples/” folder and the “example.spec.ts” file within the “tests” folder. DO NOT DELETE THE “tests” FOLDER.
Basic Navigation with Playwright
In this chapter, we will delve into the basics of web testing automation using Playwright. Learn how to navigate between pages, interact with page elements, and perform basic automation actions such as clicks and form filling.
In the “tests” folder, create a file named “amazonHome.spec.js.”
In the file, add the following code:
import { test, expect } from '@playwright/test';
test.use({
locale: 'pt-BR',
headless: true
});
test.beforeEach(async ({ page }) => {
global.page = page
});
test.afterEach(async ({ page }) => {
await page.close();
});
test('Validar tela principal da amazon', async () => {
await test.step('Navego para tela principal da amazon.com', async () => {
await page.goto('https://www.amazon.com.br/');
})
await test.step('Tela principal da amazon é apresentada', async () => {
const currentUrl = page.url();
expect(currentUrl).toBe('https://www.amazon.com.br/')
})
await test.step('Valido tela principal da amazon', async () => {
await page.waitForSelector('#nav-logo-sprites');
const logoElement = page.locator('#nav-logo-sprites');
const searchInput = page.locator('#twotabsearchtextbox');
const searchButton = page.locator('.nav-search-submit');
await expect(logoElement).toBeVisible();
await expect(searchInput).toBeVisible();
await expect(searchButton).toBeVisible();
})
});
Explaining the Above Steps:
- In the “step” ‘Navego para tela principal da amazon.com’:
We are using Playwright to navigate to the main screen of the Amazon website (https://www.amazon.com.br/). The page.goto
command is used to load the desired URL in the browser.
When executing this code snippet, Playwright will open the browser and load the main Amazon page. This step is crucial to initiate automation tests and ensure that all subsequent interactions take place on the correct page
- In the “step” ‘Tela principal da amazon é apresentada’:
In this code snippet, we are verifying if the main screen of Amazon is being displayed correctly. We use Playwright to obtain the current URL of the page through page.url()
, and then use the expect function to compare if the current URL is exactly equal to „https://www.amazon.com.br/„.
Checking the current URL is an effective way to confirm if the main screen of Amazon is displayed as expected. If the URL does not match the expected one, the test will fail, indicating the need for investigation and correction.
- In the “step” ‘Valido tela principal da amazon’:
In this code snippet, we are validating the main screen of Amazon by checking the presence and visibility of important elements. We use Playwright to wait for the existence of these elements using page.waitForSelector
. Next, we assign these elements to their respective locators: logoElement
, searchInput
, and searchButton
.
We use the expect
function to ensure that these elements are visible on the screen. With the await expect(logoElement).toBeVisible()
, we validate if the logo element is visible. The same is done for the search field and the search button. If any of these elements is not visible, the test will fail, indicating the need for investigation and correction.
This step is essential to ensure that the fundamental elements of the main screen of Amazon are present and visible, ensuring that the page is rendered correctly and ready for interaction.
Running Tests
To run the test, simply use the command:
npx playwright test
Then you will see the following happen:
Now we will see the steps it took using Playwright’s debug mode:
We can observe in the video that it checks for the existence of the indicated elements and successfully completes the test, with all tests passing.
Conclusion
In this article, we covered everything from the introduction to Playwright to setting up the development environment. We explored basic navigation with Playwright, demonstrating how to interact with page elements, such as clicks and form filling. Additionally, we learned how to run tests using Playwright and how to verify the existence and visibility of important elements.
However, this was just the first part of our guide on test automation with Playwright. In the next part, we will delve into the use of the Page Object concept, an approach that aims to make tests more structured, reusable, and easy to maintain.
By adopting the Page Object concept, your team can create more robust, flexible, and maintainable tests. Reusing encapsulated objects and interactions in Page Objects promotes scalability and efficiency in testing, allowing you to adapt to changes in the application more agilely and reliably.
Sources and Useful Links
Fast and reliable end-to-end testing for modern web apps | Playwright
Download | Node.js (Node.js.org)
LinkedIn: Rodrigo Cabral | LinkedIn
GitHub: RodrigoOBC (Rodrigo de Brito de Oliveira Cabral) · GitHub