ScreenshotNeo

BlogHow-to

How to Set Up Playwright in Visual Studio

Set up Playwright in Visual Studio Code, install browsers, run your first test, debug failures, and automate screenshots reliably.

By the ScreenshotNeo team1 October 20269 min read

Short clarification: Playwright’s official editor setup guide covers Visual Studio Code (VS Code). The steps below assume VS Code; the researched documentation does not verify an equivalent setup path for the full Visual Studio IDE. Playwright uses Node.js and npm, so install Node.js first, then add the Playwright extension or initialize the project from a terminal.

What you need before installing Playwright

  • Visual Studio Code.
  • Node.js, preferably the LTS release recommended by the Playwright VS Code guide.
  • A new or existing project folder. For an existing application, open its root folder in VS Code so dependencies and configuration belong to that project.

Open a new terminal and verify Node.js and npm are available:

node --version
npm --version

VS Code’s Node.js tutorial explains that Node.js provides the runtime and npm is its package manager. If either command is not found, install Node.js and start a new terminal before continuing.

Option 1: Install Playwright from the VS Code extension

  1. Open VS Code.
  2. Open Extensions with Ctrl+Shift+X on Windows/Linux or Cmd+Shift+X on macOS.
  3. Search for Playwright and install the official Playwright extension from Microsoft.
  4. Open the Command Palette with Ctrl+Shift+P or Cmd+Shift+P.
  5. Run Test: Install Playwright.
  6. Choose the browsers your tests must cover, such as Chromium, Firefox, or WebKit.
  7. Choose whether to add a GitHub Actions workflow when prompted.
  8. Allow the initializer to install browser binaries when prompted.

The extension creates the project configuration and exposes the Testing view. Open the Testing icon in the Activity Bar to see the generated example test and browser projects. These steps follow Playwright’s VS Code guide.

Option 2: Initialize Playwright from a terminal

The terminal route is useful when you want setup recorded explicitly in a repository, or when you are adding Playwright to an existing application. Run one of the documented initializers from the project directory:

npm init playwright@latest

Yarn and pnpm alternatives are:

yarn create playwright
pnpm create playwright

The initializer asks whether to use JavaScript or TypeScript, where to put tests (usually tests, or e2e if a tests directory already exists), whether to add GitHub Actions, and whether to install browser binaries. It creates a Playwright configuration file, package metadata and lock files, and an example spec. See the Playwright installation guide for the current prompts and supported setup.

Install or update Playwright browsers

Playwright browser binaries are version-coupled to the Playwright package. Install the default browser set with:

npx playwright install

Install only Chromium when that is all your test suite needs:

npx playwright install chromium

On Linux or in CI environments, install operating-system dependencies too:

npx playwright install-deps
npx playwright install --with-deps chromium

Playwright downloads browsers from Microsoft’s CDN by default. Corporate proxies, firewalls, or custom certificate policies can block that download; configure the network according to the browser installation documentation.

After updating Playwright, check the installed version and reinstall matching browsers if needed:

npx playwright --version
npm install -D @playwright/test@latest
npx playwright install

Use the current stable Playwright system-requirements page for exact supported Node.js versions and operating systems because those requirements change over time.

Understand the generated project

A typical project contains:

  • playwright.config.ts or a JavaScript equivalent for browser projects, retries, reporters, timeouts, and shared settings.
  • tests/ or e2e/ containing test specifications.
  • package.json and a lock file recording the Playwright dependency.
  • Installed browser binaries managed by Playwright.

A minimal TypeScript configuration can look like this:

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',
  use: {
    baseURL: 'https://example.com',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure'
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit', use: { ...devices['Desktop Safari'] } }
  ]
});

Adjust the projects to match the browsers your users and CI machines require. Installing fewer browsers reduces download size and setup time, while testing more projects increases coverage.

Write and run your first Playwright test

Create tests/home.spec.ts:

import { test, expect } from '@playwright/test';

test('home page has the expected title', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page).toHaveTitle(/Example Domain/);
});

Run it from a terminal:

npx playwright test

Run a specific browser project:

npx playwright test --project=chromium

Run one file or one test by name:

npx playwright test tests/home.spec.ts
npx playwright test -g "home page"

Playwright documents the command-line workflow in its running and debugging tests guide.

Run tests inside VS Code

  1. Open the Testing view from the Activity Bar.
  2. Expand the project and browser project you want to run.
  3. Click the play button beside a test, file, or project.
  4. Use the browser project controls to switch between Chromium, Firefox, and WebKit configurations.

The extension lets you run one test, an entire file, or the project without leaving the editor. The first successful run should show a passing example test and identify the browser project that executed it.

Debug a test with breakpoints

  1. Open a test file and click in the gutter to set a breakpoint.
  2. Open the Testing view.
  3. Use the test’s menu and choose Debug Test.
  4. Inspect the browser state when execution pauses.

This is useful for checking locators, page state, request timing, and values returned by the application before an assertion fails.

Record interactions with Playwright code generation

In the Testing sidebar, choose Record new. Playwright opens a browser and records your interactions into a test. The generator prioritizes role, text, and test-id locators and improves a locator when several elements match. You can also use the codegen documentation at playwright.dev/docs/codegen.

Treat generated code as a starting point. Replace fragile CSS paths with user-facing roles or stable test IDs, remove unnecessary waits, and keep each test focused on one behavior.

Inspect failures with traces

Configure tracing for retries or failures:

use: {
  trace: 'on-first-retry'
}

The VS Code workflow and trace viewer can show a step timeline, DOM snapshots, network requests, console messages, and screenshots. This gives you evidence for whether a failure came from navigation, a locator, a request, or an assertion.

Browser, project, and execution options

Need Configuration or command Why it matters
Choose browsers projects in playwright.config.ts Run the same tests against Chromium, Firefox, WebKit, or selected device profiles.
Set a base URL use.baseURL Use relative paths such as page.goto('/login').
Capture screenshots screenshot: 'only-on-failure' Keep failure evidence without storing an image for every passing test.
Record video video: 'retain-on-failure' Preserve a recording when a test fails.
Collect traces trace: 'on-first-retry' Reduce artifact volume while retaining diagnostic detail for flaky failures.
Retry CI failures retries: process.env.CI ? 2 : 0 Separate transient failures from consistently reproducible defects.
Run in parallel fullyParallel: true Reduce wall-clock time when tests are isolated and the CI machine has capacity.
Limit a run --project, file path, or -g Shorten local feedback while developing one area.

Common setup errors and fixes

Error or symptom Likely cause Fix
node or npm is not recognized Node.js is missing or the terminal has an old PATH. Install the Node.js LTS release, open a new terminal, and rerun node --version.
Executable browser is missing Playwright package is installed but browser binaries were not. Run npx playwright install, or install the required browser explicitly.
Browser download fails Proxy, firewall, certificate, or restricted network policy. Configure the proxy or certificate policy and retry; consult the Playwright browser installation guide.
Linux launch fails with missing shared libraries System dependencies are absent. Run npx playwright install-deps or npx playwright install --with-deps chromium.
Tests do not appear in Testing view The extension is missing, the wrong folder is open, or the test file is outside testDir. Install the official extension, open the repository root, and check testDir and file naming.
A test passes locally but fails in CI Different browser binaries, OS dependencies, environment variables, timing, or network access. Install browsers in CI, use the same Playwright version, enable traces on retry, and inspect the first failing step.
Locator matches multiple elements The selector is not unique. Use a role, label, text, or test ID that identifies one element; codegen can suggest a more specific locator.
Navigation times out The site is slow, unavailable, blocked, or waiting on resources. Check the URL and network policy, wait for the right readiness condition, and raise a timeout only when the page legitimately needs longer.
Tests are flaky in parallel Tests share state, ports, accounts, files, or mutable data. Isolate fixtures and data, or reduce parallelism for the shared resource.

Performance, reliability, and cost considerations

  • Install only needed browsers: Chromium alone is faster to download than the full browser set, but cross-browser projects provide broader coverage.
  • Reuse configuration: Put shared settings in playwright.config.ts instead of duplicating them in every test.
  • Parallelize safely: Parallel workers reduce elapsed time only when tests do not contend for shared state.
  • Keep diagnostics targeted: “On first retry” traces and failure-only screenshots reduce artifact storage and report noise.
  • Pin versions in CI: Keep the package lock file and install matching browsers after Playwright upgrades.
  • Budget for browser downloads: CI caches can reduce repeated downloads, while clean environments pay the setup cost each run.
  • Prefer explicit readiness: Wait for a selector, URL, or application state rather than adding arbitrary sleeps.

Or skip the browser setup

If your goal is a clean website image rather than end-to-end browser assertions, ScreenshotNeo provides a one-request screenshot API. Its capture flow accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Each step can be turned off.

Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and every response identifies the result with X-Page-Verdict and X-Billed headers. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo includes full-page capture with lazy images loaded, element capture by CSS selector, dark mode, device presets, custom viewports, retina scale, PDF output, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, usage reporting, and an OpenAPI specification. It supports the parameter names used by other screenshot APIs to simplify switching.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account.

FAQ

Does this guide apply to the full Visual Studio IDE?

The documented editor workflow is for Visual Studio Code. The research does not verify an equivalent setup path for the full Visual Studio IDE.

Should I use the extension or the terminal initializer?

Use the extension for an editor-led workflow. Use the package-manager initializer when you want setup commands and generated files to be explicit in the repository or when adding Playwright to an existing project.

Why do browser binaries need a separate install?

The Playwright package and its browser binaries are version-coupled. Installing the package does not always mean the matching browsers are present, especially in a fresh CI environment.

Can I run only Chromium?

Yes. Install it with npx playwright install chromium and configure only the Chromium project when that matches your coverage needs.

Where should I look when a test fails only in CI?

Check browser installation, operating-system dependencies, proxy access, environment variables, test isolation, and a trace captured on the first retry.