1. Install Playwright in VS Code
- Open VS Code.
- Open the terminal (
Ctrl + ~). - Run the following command to install Playwright:
npm init playwright@latest
2. Create a Playwright Test File
Create a test file inside the tests/ folder, e.g., google-search.spec.ts:
import { test, expect } from '@playwright/test';
test('Google Search Test', async ({ page }) => {
// Open Google
await page.goto('https://codehelpbyasmi.com');
// Type "Playwright testing" in the search bar
await page.fill('input[name="q"]', 'Playwright testing');
// Press "Enter" to search
await page.press('input[name="q"]', 'Enter');
// Wait for the search results to load
await page.waitForSelector('#search');
// Validate the page title contains "Playwright"
expect(await page.title()).toContain('Playwright');
});
3. Run Playwright Tests in VS Code
- Open the VS Code Terminal (
Ctrl + ~). - Run the test using:
npx playwright test
- To run tests in headed mode (UI visible):
npx playwright test --headed
- To run a single test file:
npx playwright test tests/example.spec.ts
4. Debugging Playwright Tests in VS Code
VS Code provides powerful debugging features for Playwright.
Enable Debugging
- Open your test file in VS Code.
- Add a debugger statement inside the test:
test('Google search test', async ({ page }) => { await page.goto('https://codehelpbyasmi.com'); debugger; // Execution will pause here await page.fill('input[name="q"]', 'Playwright testing'); });
- Run the test in debug mode:
npx playwright test --debug
Use VS Code Debugger
- Open Run and Debug Panel (
Ctrl + Shift + D). - Click “Run Playwright Test” or create a
.vscode/launch.json:
{ "version": "0.2.0", "configurations": [ { "name": "Run Playwright Tests", "type": "node", "request": "launch", "program": "${workspaceFolder}/node_modules/.bin/playwright", "args": ["test"], "console": "integratedTerminal" } ] }
- Click “Start Debugging” (
F5).
5. Use Playwright Codegen in VS Code
Playwright provides a test recorder that automatically generates code for your actions:
npx playwright codegen example.com
- It launches a browser and records your interactions.
- The generated test code can be copied into your project.
6. Playwright Test Explorer (VS Code Extension)
To make running and debugging tests easier:
- Install the Playwright Test for VS Code extension.
- Click on the Testing tab (
Ctrl + Shift + P, search “Show Test Explorer”). - Run tests directly from the UI.
