Writing First Playwright Test
Writing First Playwright Test
Playwright is a powerful end-to-end testing framework developed by Microsoft that allows automated testing of web applications across different browsers. It supports multiple programming languages like JavaScript, TypeScript, Python, and more. Playwright is designed for reliability, speed, and ease of use.
Before writing your first Playwright test, ensure you have Node.js installed on your system. Playwright requires Node.js for execution.
Follow these steps to set up Playwright and write your first test:
Write a Test Script Using Playwright
Install Playwright
Open a terminal and run the following command to install Playwright:
/> npx playwright install
Detailed steps are outlined here.
Create a New Test File
Create a new JavaScript or TypeScript file, for example, example.test.js
.
Write a Simple Test
Open example.test.js
and add the following test script:
const { test, expect } = require('@playwright/test');
test('Open Google and verify title', async ({ page }) => {
await page.goto('https://www.google.com');
await expect(page).toHaveTitle(/Google/);
});
Configuration Files and Browsers
Playwright uses a configuration file named playwright.config.js
or playwright.config.ts
to manage settings like browser selection, timeouts, and test directories.
Example playwright.config.js
file:
module.exports = {
use: {
browserName: 'chromium', // Options: chromium, firefox, webkit
headless: false, // Run in headed mode
},
};
Run the Test
To execute the test, run the following command in the terminal:
/> npx playwright test example.test.js
This will launch the browser, perform the test, and display the results in the console.
Congratulations! You have successfully written and executed your first Playwright test.
Playwright provides extensive capabilities for automating web applications, including handling UI interactions, capturing screenshots, and parallel test execution.