Writing Your First Playwright Test
Writing Your First Playwright Test
Playwright is a powerful end-to-end testing framework developed by Microsoft. It allows you to automate web browsers such as Chrome, Firefox, and Safari with a single API. In this guide, we'll walk you through the steps to write your first Playwright test using JavaScript or TypeScript.
Step 1: Install Playwright
First, you need to install Playwright in your project. You can do this using npm:
bash
Copy
Edit
npm init -y
npm install -D @playwright/test
npx playwright install
The last command installs the necessary browser binaries.
Step 2: Create a Test File
Create a new file, for example, example.spec.js or example.spec.ts (if using TypeScript), and add the following code:
javascript
Copy
Edit
// example.spec.js
const { test, expect } = require('@playwright/test');
test('basic test', async ({ page }) => {
await page.goto('https://example.com');
const title = await page.title();
expect(title).toBe('Example Domain');
});
This test:
Opens a browser.
Navigates to https://example.com.
Asserts that the page title is "Example Domain".
Step 3: Run the Test
To run your test, use the following command:
bash
Copy
Edit
npx playwright test
Playwright will detect any files that match the pattern *.spec.js or *.spec.ts and execute them.
Step 4: View the Test Report
After running the tests, Playwright generates a summary in the terminal. You can also open the detailed HTML report using:
bash
Copy
Edit
npx playwright show-report
This opens a visual report in your default browser, showing test results, screenshots, and more.
Bonus: Run Tests in UI Mode
To observe the browser while tests are running, use UI mode:
bash
Copy
Edit
npx playwright test --ui
This launches a test runner with a graphical interface—perfect for debugging.
Conclusion
Writing your first Playwright test is simple and quick. With just a few lines of code, you can start automating your web application. As you grow more comfortable, you can explore features like parallel testing, tracing, screenshots, and cross-browser support.
Would you like help with setting up Playwright using TypeScript or configuring tests for a specific framework like React or Angular?
Learn Playwright Course in Hyderabad
Read More
Understanding Browsers Supported by Playwright
Setting Up Your First Playwright Project
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment