User Agents

Web browsers and everyday web tech, explained

Testing Websites with Playwright and Puppeteer

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Testing websites in a headless browser allows you to automate interactions, verify UI elements, and perform end-to-end testing without the overhead of a visible browser window. By using Playwright or Puppeteer, you can programmatically navigate pages, click buttons, fill out forms, and capture screenshots to ensure your site functions correctly across different environments. This approach is essential for Continuous Integration (CI) pipelines where a graphical user interface is unavailable.

What You'll Need

  • Node.js: Installed on your machine (LTS version recommended).
  • npm or yarn: Package managers that come bundled with Node.js.
  • A Code Editor: Visual Studio Code is recommended for its excellent JavaScript/TypeScript support.
  • A Target Website: A local development URL or a live staging site to test.

Step-by-Step

  1. Choose Your Library: Decide between Puppeteer and Playwright. Puppeteer is excellent for Chrome-specific automation and scraping. Playwright is more versatile, offering native support for Chromium, Firefox, and WebKit (Safari) within a single API.
  2. Initialize Your Project: Create a new directory for your tests, navigate into it via the terminal, and run npm init -y to create a package.json file.
  3. Install the Dependencies:
    • For Playwright: Run npm init playwright@latest. This command installs the library, the necessary browser binaries, and sets up a sample test folder.
    • For Puppeteer: Run npm install puppeteer. This will download the compatible version of Chromium.
  4. Create a Basic Test Script: Create a file (e.g., test.spec.js for Playwright or script.js for Puppeteer). Write a script that launches the browser, opens a new page, and navigates to your URL.
  5. Implement Assertions: Define what "success" looks like. For example, check if the page title contains a specific word, or verify that a login button is visible and clickable.
  6. Interact with Elements: Use selectors (CSS or XPath) to find elements. Use methods like .click(), .fill(), or .type() to simulate user behavior.
  7. Execute in Headless Mode: By default, both libraries run headlessly. Run your script via the terminal (e.g., npx playwright test or node script.js). The browser will run in the background, and results will be printed to the console.
  8. Capture Evidence: Add commands to take screenshots (page.screenshot()) or generate PDF reports when a test fails. This is critical for debugging headless failures.

Common Mistakes

  • Ignoring Asynchronous Execution: Both libraries rely heavily on Promises. Forgetting the await keyword before a browser action will cause the script to move to the next line before the previous action finishes, leading to "element not found" errors.
  • Using Fragile Selectors: Relying on long, absolute XPath expressions (e.g., /html/body/div[1]/div[2]/span) makes tests break whenever a small layout change occurs. Use stable IDs or data-test attributes.
  • Over-reliance on Static Timeouts: Using setTimeout or page.waitForTimeout() is inefficient. It slows down tests and can still fail if the network is slower than your hardcoded limit.
  • Forgetting to Close the Browser: If you do not call browser.close() at the end of your script, you may leave zombie browser processes running in the background, consuming system memory.

Tips

  • Use Headed Mode for Debugging: When a test fails in headless mode, switch headless: false in your configuration. This allows you to watch the browser perform the actions in real-time to identify where it goes wrong.
  • Leverage Auto-waiting: Playwright has built-in auto-waiting, meaning it waits for an element to be actionable before clicking. Use this instead of manual sleep timers.
  • Implement Parallelization: To speed up large test suites, run tests in parallel. Playwright supports this natively, allowing you to run multiple browser contexts simultaneously.
  • Use Data-Test Attributes: Add data-testid="submit-button" to your HTML elements. This creates a contract between developers and testers that these attributes won't change, ensuring stable selectors.

Troubleshooting

If your tests are failing or the browser is not launching, try the following steps:

  • Check Browser Binaries: If you get an error saying the browser cannot be found, run npx playwright install to ensure all required browser engines are downloaded.
  • Inspect Network Logs: Use the page.on('requestfailed') listener to see if the browser is failing to load CSS or JS files, which might be preventing elements from appearing.
  • Check for Iframes: If you cannot find an element that you can clearly see in the browser, check if it is inside an <iframe>. You must switch the context to the frame before interacting with its contents.
  • Adjust User-Agent: Some websites block headless browsers. Try setting a custom User-Agent string in the browser context to mimic a standard desktop browser.

Frequently Asked Questions

What is the main difference between Playwright and Puppeteer?

Puppeteer primarily supports Chrome/Chromium. Playwright, developed by many of the same engineers, supports Chromium, Firefox, and WebKit, and generally offers more robust auto-waiting features.

Can I run these tests on a Linux server without a GUI?

Yes, that is the primary purpose of headless mode. You may need to install a few system-level dependencies (libraries like libnss3 or libatk) on your Linux distribution to allow the browser engine to run.

How do I handle pop-ups or alerts?

Both libraries provide event listeners for dialogs. You can define a handler that automatically clicks "Accept" or "Dismiss" whenever a browser dialog appears.

Is headless testing slower than API testing?

Yes, headless browser testing is significantly slower because it must render the DOM and execute JavaScript. It is best used for critical user paths rather than every single edge case.

How do I test different screen sizes?

You can set the viewport option when creating a new page or browser context. This allows you to simulate mobile devices, tablets, or specific desktop resolutions.