How to Run a Playwright Script in VS Code
Run Playwright in VS Code with the Testing sidebar, terminal commands, browser projects, debugging, traces, and fixes for common errors.
Short answer: open a Playwright project in VS Code, install Microsoft’s Playwright extension, run Test: Install Playwright from the Command Palette, then use the Testing sidebar’s play or debug controls. You can also run the same script from the integrated terminal with npx playwright test.
This guide covers first setup, one test, one file, a whole suite, Chromium/Firefox/WebKit projects, headed runs, breakpoints, traces, configuration, and common failures.
1. Prerequisites and project setup
- Install an LTS release of Node.js and Visual Studio Code.
- Create or open a project folder in VS Code. A terminal-only starter is:
mkdir playwright-vscode-demo
cd playwright-vscode-demo
npm init -y
npm install --save-dev @playwright/test
npx playwright install
For an existing project, keep its package manager and scripts. Browser binaries must be installed for each browser project you intend to run.
- Open Extensions (
Ctrl+Shift+Xon Windows/Linux orCmd+Shift+Xon macOS) and install Microsoft’s official Playwright VS Code extension. - Open the Command Palette (
Ctrl+Shift+P/Cmd+Shift+P) and choose Test: Install Playwright. Select Chromium, Firefox, WebKit, or any combination. The wizard can also add a GitHub Actions workflow.
The scaffold normally creates playwright.config.ts, package metadata, and an example test directory. The config is the source of truth for test directories, projects, timeouts, retries, reporters, and browser options.
2. Create a runnable Playwright test
Save this as tests/home.spec.ts:
import { test, expect } from '@playwright/test';
test('home page has a title', async ({ page }) => {
await page.goto('https://playwright.dev/');
await expect(page).toHaveTitle(/Playwright/);
});
test('docs link opens documentation', async ({ page }) => {
await page.goto('https://playwright.dev/');
await page.getByRole('link', { name: 'Get started' }).click();
await expect(page).toHaveURL(/.*intro/);
});
Prefer role, label, text, and test-id locators. Put shared settings in playwright.config.ts:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
timeout: 30_000,
expect: { timeout: 5_000 },
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
reporter: [['html', { open: 'never' }], ['list']],
use: {
baseURL: 'https://playwright.dev',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
headless: true,
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
});
With baseURL, page.goto('/') resolves to the configured site. Store credentials in environment variables or CI secrets, never in the config.
3. Run a script or test in VS Code
Run one test
- Open the Testing icon in the Activity Bar.
- Expand the file and click the green play button beside the test name.
- Use the project checkboxes in the Playwright sidebar to choose Chromium, Firefox, WebKit, or multiple projects.
Run one file or the entire suite
Click the play button beside a test file to run that file. Click the top-level play button to run every discovered test.
Run from the integrated terminal
# all tests
npx playwright test
# one file
npx playwright test tests/home.spec.ts
# one test by title
npx playwright test -g "home page has a title"
# one configured browser project
npx playwright test --project=firefox
# visible browser
npx playwright test --headed
# interactive debugging
npx playwright test --debug
Use the sidebar for discovery, one-test runs, and debugging. Use terminal commands for package scripts, repeatable runs, and CI.
4. Choose browsers and headed mode
Each entry in projects is an independent configuration. The sidebar’s project checkboxes map to these names. To add mobile emulation:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'mobile-chrome', use: { ...devices['Pixel 5'] } },
],
});
Keep headless: true for routine runs. Use --headed or set headless: false while diagnosing navigation, responsive layouts, or browser-specific behavior. Headed mode requires a graphical session and is usually slower in CI.
5. Debug and author tests in VS Code
- Set a breakpoint by clicking beside a line number.
- Right-click a test in the Testing sidebar and choose Debug Test.
- Inspect variables, the call stack, and locator results when execution pauses.
- Use Show Trace Viewer after a run. Traces can include actions, snapshots, console messages, and network details.
The Playwright sidebar also includes Pick locator, Record new, and Record at cursor. Generated code generally prioritizes role, text, and test-id locators. Simplify recorded locators that encode incidental markup.
npx playwright show-trace test-results/**/trace.zip
For interactive authoring, npx playwright codegen https://your-site.example opens a browser and generates actions. Protect private accounts and data while recording.
6. Configuration that affects a VS Code run
| Setting | What it controls | Practical choice |
|---|---|---|
testDir |
Where tests are discovered | Point it at the directory containing *.spec.ts files. |
projects |
Browsers, devices, and variants | Give each browser a stable name. |
timeout |
Maximum time for one test | Keep it bounded and fix slow steps. |
expect.timeout |
Maximum assertion wait | Use a separate, usually shorter, budget. |
retries |
Re-runs after failure | Allow limited CI retries and investigate flakes. |
workers |
Parallel test processes | Reduce when resources or shared state require it. |
use.trace |
Trace capture policy | on-first-retry preserves failure evidence. |
webServer |
Starts a local app | Configure command, URL, and reuse policy. |
webServer: {
command: 'npm run dev',
url: 'http://127.0.0.1:3000',
reuseExistingServer: !process.env.CI,
},
7. Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
| No tests in Testing | Playwright is missing, the wrong folder is open, or testDir is wrong. |
Open the project root, run npm install, check config and filenames, then reload VS Code. |
| Executable does not exist | The selected browser binary is not installed. | Run Test: Install Playwright or npx playwright install. |
| Wrong browser runs | A different project is selected. | Check the sidebar project and use its exact name with --project. |
| Locator timeout | Ambiguous locator, page not ready, or genuinely slow app. | Use role/label/test-id locators and wait for meaningful state instead of arbitrary sleeps. |
| Works headed but fails headless | Timing, viewport, permissions, or visible-UI assumptions. | Compare trace and screenshots; configure viewport or permissions explicitly. |
| Breakpoints are skipped | The test was run normally. | Choose Debug Test, save files, and restart the run. |
| No trace | Tracing is disabled. | Set trace: 'on-first-retry' or temporarily 'on'. |
| Local server refused | The app is not running or URL/port is wrong. | Verify the app, port, webServer.url, and baseURL. |
| Tests interfere | Shared accounts, files, or mutable data. | Isolate data, use fixtures, or reduce workers. |
8. Speed, reliability, and cost choices
- Speed: run one project during development, keep browsers headless, and avoid video or full traces on passing tests.
- Reliability: use web-first assertions such as
toBeVisibleandtoHaveURL, isolate data, and retain traces on failure. - Parallelism: multiple workers shorten independent suites but increase CPU, memory, and server load.
- Cost: Playwright and its VS Code extension are free developer tools. Practical costs are machine or CI minutes, browser downloads, and hosted infrastructure.
9. Or skip the browser setup
If you need a clean image or PDF rather than an interactive test, ScreenshotNeo provides a website screenshot API. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
One GET request returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API docs for all options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Features include full-page and element capture, dark mode, device presets or custom viewports, retina scale, PDF controls, HTML/CSS rendering, custom CSS/JavaScript, clicks, waits, blocking rules, headers/cookies/user agent/Authorization, timezone/geolocation, transparent backgrounds, resizing, cache TTL, signed links, async jobs with signed webhooks, bulk capture of 100 URLs per call, a usage API, and an OpenAPI spec. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000.
Create a free ScreenshotNeo account and get 1,000 screenshots a month with no card.
10. FAQ
Can I run a plain Playwright script with no test?
Yes. Put browser code in a Node entry file and run it with node script.mjs, or wrap it in test() so VS Code can discover and debug it.
How do I run only Firefox and WebKit?
Select those projects in the sidebar, or run npx playwright test --project=firefox and the equivalent WebKit command.
Where are screenshots and reports saved?
Artifacts commonly go under test-results. Open the HTML report with npx playwright show-report.
Should I use VS Code or the terminal?
Use VS Code for discovery, one-test runs, breakpoints, locator picking, and traces. Use the terminal for repeatable commands, package scripts, and CI.


