Playwright is the first name that comes to mind when considering an efficient and reliable automation testing framework. It works great for testing online applications essential to our day-to-day existence. These apps, which include banking and online shopping, simplify and ease our lives. Therefore, as a business owner, it becomes essential for you to ensure that your app works well across various platforms.
However, this is only possible through rigorous testing. Even though Playwright is new to the testing world, its user-friendly interface has helped it gain popularity among developers and testers. This tool is more interesting because it allows developers to automate all web browsers using a single API.
Additionally, Playwright testing is open-source software that supports multiple programming languages like Java, Python, NodeJS, and C#. Some other notable features of Playwright include iframe support, built-in reporters, selectors support, and shadow DOM. Overall, Playwright enhances the productivity and accuracy of the testing process. It also assists businesses in developing trust with their customers.
So, let’s get started and discover more about the Playwright’s function in test automation.
Exploring Playwright To Streamline Browser Automation For Modern App Development
Today, Playwright is widely used to automate browser tests across various platforms and web- browsers. This software uses modern technologies like Webkit and Chromium engines. These engines render web pages and handle interactions within web browsers. By utilizing these engines, Playwright testing companies benefit from their high reliability and efficiency. Further, Playwright offers an easy-to-use interface for managing browsers, thus ensuring that tasks get completed quickly, reliably, and with minimal complexity.
Why Choose Playwright For Web Automation?
The Playwright addresses common challenges in web automation, such as slow test execution, unreliable wait scenarios, excessive boilerplate code for browser setup, and difficulties with parallel execution. Playwright offers several advantages that make it a preferred choice for web automation, as explained below:
- Ease of Installation: Playwright simplifies setup with a single command that downloads binaries for supported browsers such as Chromium, Firefox, and Webkit.
- Core Concepts: Browser, Context, and Page, the playwright testing tool operates on these three core concepts.
- Browser: Launches a browser instance (Chromium, Firefox, Webkit) using the Browser class.
- Context: Enables parallelization via isolated browser contexts, akin to incognito sessions.
- Page: Represents a tab or pop-up window within a context where test actions occur.
- Cross-Browser Support: Playwright’s compatibility with multi-browser allows testers to create tests once and execute them across different browsers with minimal configuration. It reduces the development effort and ensures consistency in the results.
- Playwright’s Auto-Wait Feature and Reliable Execution: One significant benefit of Playwright is its automatic wait function. This feature waits for the website’s parts to be downloaded before performing any action.
- Custom Waiting in Playwright: Playwright provides testing automation companies with unique wait capabilities so they can bide their time till a selector becomes available. It is beneficial for scenarios like lazy page loading. Additionally, it supports waiting until specific network conditions are met.
- Authentication Handling: Playwright simplifies authentication by enabling users to log in once and store session details and cookies within a context. This stored information can be utilized across all tests within that context, eliminating the need for multiple logins. Integrating this code into setup files (for Jest) or test fixtures (for a playwright-test runner) is essential to apply it consistently across context objects.
- Resilient Selectors: The Playwright introduces more resilient selectors like text content and accessibility labels alongside standard selectors such as id, XPath, CSS, and class names.
Features Of The Playwright Test Automation Framework
As a versatile test automation framework, Playwright offers various benefits to automation testing companies. These features make Playwright a comprehensive and reliable choice for test automation. They further ensure efficient and accurate testing of web applications across various scenarios and browsers.
No Flaky Tests and Resilience
Playwright’s auto-wait feature monitors items before executing actions, reducing the need for arbitrary timeouts, frequently resulting in flaky tests. It also provides introspection events, ensuring tests are resilient and reliable.
Web-Specific Assertion Tests
Developers can create web-specific assertions with Playwright, which allows automatic retries until conditions are met. It also includes test retries, capturing traces, screenshots, and videos to eliminate test failures.
Free Of Test Runner Limitations
Playwright is a modern automation testing tool designed specifically for web browsers. It can run tests separately from the browser, which is very useful as it avoids the common problems that may occur when tests are run within the browser.
One Test For Multiple Scenarios
Playwright enables one test to cover scenarios involving multiple users, origins, and tabs, streamlining testing across various contexts.
Authentic Browser Input And User Simulation
The Playwright interacts with elements like a real user, including navigating frames and interacting with shadow DOM elements, ensuring realistic testing scenarios.
Skip Repetitive Logins
Playwright saves login states for reuse across automation tests. So, Playwright testing enhances test efficiency by reducing repetitive tasks.
Zero Overhead And Fast Execution
With Playwright, each test runs in a new browser profile, ensuring isolation and faster execution without the overhead.
Dynamic Tooling Options
Playwright offers tools like Codegen for creating test scripts, Trace Viewer for detailed test analysis, and the Playwright Inspector for debugging and generating selectors.
Supported Browsers
Playwright supports various modern browsers, including Firefox, Chromium, Google Chrome, Microsoft Edge, and WebKit. It is regularly updated to maintain compatibility with the latest browser versions.
How To Set Up And Run Playwright Test Scripts?
Step 1: Create a New Directory In VSCode
Create a new directory, such as “PlaywrightDemo,” in Visual Studio Code (VSCode). This approach is also preferred even by leading Playwright testing companies.
Step 2: Open Directory In VSCode
Open the newly created folder in VSCode by selecting File > Open Folder and choosing the “PlaywrightDemo” folder.
Step 3: Open Terminal In VSCode
From the VSCode menu, click on Terminal> New Terminal to open a terminal window.
Step 4: Install Playwright
In the Terminal, enter the following command to initiate the Playwright installation:
```npm init playwright@latest```
Follow the prompts to provide necessary inputs. For this tutorial, we’ll use TypeScript.
This command performs the following actions:
– Creates Package.json
– Installs necessary npm libraries
– Sets up basic files and folders:
– “tests” folder: Contains test scripts (e.g., example.spec.ts by default)
– “.gitignore”: Helps with version control using Git
– “package.json” and “package-lock.json”: Track dependencies and create shortcuts for running tests
– “playwright.config.ts”: Global configuration file for Playwright testing tool, where options can be set
Step 5: Install Playwright Browsers
While Playwright can run on existing browsers, it’s recommended to install Playwright’s versions of Chromium, Firefox, and Webkit using the command:
```npx playwright install```
Step 6: Create Your First Playwright Test
Navigate to the “tests” folder and create a new test spec file, e.g., “demo.spec.ts.”
Here’s an example scenario for your test:
```typescript
//demo.spec.ts
import { test, expect } from '@playwright/test';
test('Verify Login Error Message', async ({ page }) => {
await page.goto('https://www.browserstack.com/');
await page.waitForSelector('text=Sign in', { state: 'visible' });
await page.click('text=Sign in');
await page.waitForSelector('#user_email_login');
await page.type('#user_email_login', '[email protected]');
await page.type('#user_password', 'examplepassword');
await page.click('#user_submit');
const errorMessage = await (await page.locator("//input[@id='user_password']/../div[@class='error-msg']").textContent()).trim();
console.log("Browserstack Login Error Message: "+errorMessage);
expect(errorMessage).toBe('Invalid password');
});
```
Step 7: Execute Your Playwright Automation Testing
Modify the “playwright.config.ts” file to comment out the option that starts with “projects: [“.
Then, execute your Playwright test script using the following command:
```npx playwright test demo.spec.ts --headed```
Explanation:
– Specifies the test file to run (demo.spec.ts).
– Uses “–headed” to run in headed mode (visible browser).
– By default, Playwright tests run in Chromium.
Step 8: View The HTML Report
After running the test, an HTML report is generated in the “playwright-report” folder. To view the report, use the command:
```npx playwright show-report```
Test Case: Verify Job Code Auto-Population on Career Page
Test Steps:
1. Open xyz.com’s careers page via “https://www.xyz.com/careers”.
2. Choose a random job listing and obtain its job code using a random function.
3. Click the “Apply now” button on the selected job listing.
4. Confirm if the job code is automatically filled in the form’s “edit-job-id” field.
Expected Result: The job code fetched in step 2 should match the value in the “edit-job-id” field, indicating successful auto-population.
Solution:
To automate this test, we use the Playwright automation testing framework. Here’s the script (careers.spec.js) to automate testing:
```javascript
const { test, expect } = require('@playwright/test');
test('Test Job Code', async ({ browser, page }) => {
// Open the careers page
await page.goto('https://www.zyxware.com/careers');
// Find a random job teaser item
const teaserItems = page.locator('.career-openings-page-row.clearfix.views-row article');
const count = await teaserItems.count();
const randomTeaserItem = teaserItems.nth(Math.floor(Math.random() * count));
// Get job code from the teaser item
const jobCodeElement = await randomTeaserItem.locator('.field.field--field-job-code');
await expect(jobCodeElement).toHaveCount(1);
const jobCode = await jobCodeElement.innerText();
// Click on "Apply now" button
const jobLink = randomTeaserItem.locator('a');
await jobLink.click();
const applyNowButton = await page.locator('#block-careerapplyblock').getByRole('link', { name: 'Apply now' });
const popupPromise = page.waitForEvent('popup');
await applyNowButton.click();
const popup = await popupPromise;
await popup.waitForLoadState();
// Check if job code input field has correct value
const jobCodeInput = await popup.locator("#edit-job-id");
const jobCodeValue = await jobCodeInput.inputValue();
await expect(jobCodeValue).toEqual(jobCode);
});
```
To execute this test across different browsers, create a config file (playwright.config.js):
```javascript
const { devices } = require('@playwright/test');
const config = {
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
};
module.exports = config;
```
To run the test in Chrome, Firefox, and Safari, use the command:
```
npx playwright test --reporter=html
```
For a detailed report, use:
```
npx playwright show-report
```
Ending Note
Playwright testing tool is a modern framework used in software development primarily for automating web application testing, including end-to-end (E2E) testing. It ensures that developed goods have excellent functionality and performance while reducing unstable test counts, increasing testing accuracy, and expediting the quality assurance process. Consequently, teams trying to improve their testing methods must grasp Playwright and its possibilities.
Feel free to ask questions about Playwright or its integration; our expert team will gladly assist you.
AutomationQA
Latest posts by AutomationQA (see all)
- Selenium 4: What’s New and Why It Matters for Test Automation - December 24, 2024
- Cypress Plugins and Add-ons to Boost Your Test Automation - December 20, 2024
- How To Choose the Right Web App Testing Service for Your Company? - December 12, 2024