October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

How to Use Cucumber With Playwright

Cucumber.js runs Gherkin scenarios while Playwright handles browser actions. Learn the setup, step definitions, World state, hooks, concurrency, and runner trade-offs.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Cucumber.js to run Gherkin scenarios and match their steps to JavaScript or TypeScript functions; use Playwright from those functions to control a browser. Cucumber does not automate browsers itself, and this setup is support code that connects two separate tools—not a Playwright Test setting. The pattern below creates a Playwright browser context and page per Cucumber scenario, shares them through Cucumber’s scenario World, and closes the context afterward.

How Cucumber.js and Playwright fit together

The execution path is: a .feature scenario → a matching Cucumber step definition → a Playwright browser, context, and page → an assertion. The feature file describes behavior in Gherkin; support code handles browser actions and checks. Cucumber’s documentation explicitly says it is not a browser automation tool, though it works with browser automation tools such as Playwright (Cucumber browser automation).

This is Cucumber.js running scenarios with Playwright as the browser driver. It is not Playwright Test running Cucumber features. Cucumber step definitions can be asynchronous and return or await promises, so a rejected Playwright operation can fail the step (Cucumber.js step definitions).

Install the packages and browser

Start in a Node.js project. Install Cucumber.js and Playwright, then install the browser binary Playwright will launch. Package versions and runtime requirements change; use the current installation instructions rather than copying a version number from an old tutorial (Playwright installation, Playwright browsers).

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Install dependencies: npm install --save-dev @cucumber/cucumber playwright.

  2. Install Chromium for Playwright: npx playwright install chromium. For other browsers, install the corresponding supported browser binary using Playwright’s CLI.

  3. Create a feature directory and a support-code directory. The example below uses features/ for Gherkin and features/support/ for hooks and step definitions.

  4. Add a Cucumber script to package.json: "test:e2e": "cucumber-js --require features/support/**/*.js features/**/*.feature". This example assumes JavaScript support files. For TypeScript, configure Cucumber.js to load a TypeScript runtime or compile support code, following the current Cucumber.js setup documentation.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The command explicitly tells Cucumber where to find support files and feature files. Adjust the paths if your project uses another layout. Playwright’s JavaScript and TypeScript support is documented separately at Playwright supported languages.

Create a feature and connect its steps to Playwright

Feature file

Save this as features/homepage.feature:

Feature: Homepage navigation

  Scenario: A visitor opens the homepage
    Given I open the homepage
    Then the page title should contain "Example Domain"

Scenario state and hooks

Save the following as features/support/hooks.js. The browser is launched once for the Cucumber process, while each scenario receives its own browser context and page. The context is closed after the scenario so cookies and other browser state do not leak into the next one.

const { Before, After, setWorldConstructor, World } = require('@cucumber/cucumber');
const { chromium } = require('playwright');

class BrowserWorld extends World {
  async openBrowser() {
    if (!this.browser) {
      this.browser = await chromium.launch({ headless: true });
    }
    this.context = await this.browser.newContext();
    this.page = await this.context.newPage();
  }
}

setWorldConstructor(BrowserWorld);

Before(async function () {
  await this.openBrowser();
});

After(async function () {
  if (this.context) {
    await this.context.close();
  }
});

This compact example launches Chromium lazily and keeps the browser reference on the scenario World. For a small suite it is a straightforward pattern; for parallel suites, use explicit worker-aware browser ownership, described below. Cucumber creates an isolated World for each scenario, making it the natural place for scenario-specific state (Cucumber state).

Step definitions

Save this as features/step_definitions/homepage.js:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const { Given, Then } = require('@cucumber/cucumber');
const assert = require('node:assert/strict');

Given('I open the homepage', async function () {
  await this.page.goto('https://example.com');
});

Then('the page title should contain {string}', async function (expected) {
  const title = await this.page.title();
  assert.ok(title.includes(expected), `Expected title to include "${expected}", got "${title}"`);
});

Run it with npm run test:e2e. Cucumber matches each Gherkin step to its definition; the definition awaits Playwright, and a failed navigation or assertion is reported as a failed step. These definitions use Cucumber Expressions, including the {string} parameter. Cucumber.js also supports regular expressions (step definitions documentation).

Share a Playwright page between Cucumber steps

In this pattern, this.page is available to every step and hook in the same scenario because each receives that scenario’s World. Use a regular function for a step or hook that reads this; arrow functions capture their surrounding this and do not receive the World as their function context.

Keep scenario-specific objects—such as the page, context, test data, and values extracted from the UI—on the World. Avoid module-level variables for scenario state: scenarios may run in parallel, and shared mutable variables can cause one scenario to affect another.

Manage hooks, browser lifetimes, and cleanup

Hooks are the right place to create and dispose resources around scenarios. Cucumber.js runs Before hooks in definition order and After hooks in reverse order; hooks can also be filtered by tags. For example, a setup hook can use a tag expression to run only for scenarios marked @authenticated (Cucumber.js hooks).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The example closes each context in After, which isolates scenario browser state. In production code, consider making cleanup resilient if setup partly fails, and close the browser process when the worker exits. If every scenario uses a fresh browser process instead, launch it in Before and close it in After; that simplifies ownership but repeats process startup. Choose based on your suite’s lifecycle needs rather than treating one pattern as mandatory.

Handle parallel execution deliberately

When Cucumber.js runs scenarios in parallel, they execute in workers. Its BeforeAll and AfterAll hooks run once per worker by default, not once for the entire run. A browser created in a worker-level hook can be reused by that worker’s scenarios, while each scenario still gets its own context and page. Shared services, test accounts, and data must also be safe for concurrent use.

The hook documentation on Cucumber.js’s main branch includes newer options, including coordinator targeting; availability depends on the installed release. Check the hooks documentation for the Cucumber.js version in your project before relying on version-sensitive features (hooks documentation).

Choose Cucumber.js or Playwright Test

Playwright recommends its own runner for Node.js. Choose Cucumber.js when the team needs Gherkin scenarios as a shared behavior specification or already has a Cucumber workflow. Choose Playwright Test when its own runner and integrated tooling are a better fit. With Cucumber.js, your project owns the glue code, browser lifecycle, and concurrency strategy; Playwright Test projects do not automatically configure Cucumber scenarios (Playwright supported languages, Playwright projects).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Decision point Cucumber.js with Playwright Playwright Test
Scenario format Gherkin feature files matched to step definitions Playwright’s own test format
Runner Cucumber.js runs scenarios; support code calls Playwright Playwright’s Node.js test runner
Best fit Teams that need behavior-readable scenarios or an existing BDD workflow Teams that prefer Playwright’s runner and integrated tooling
Browser lifecycle Set up and maintained in your Cucumber hooks and World Managed in the Playwright Test model
Cross-browser configuration Requires your own Cucumber/browser configuration Playwright projects group browser and environment configurations; this does not wire Cucumber into the runner
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

  • Cucumber reports an undefined step: confirm the step text matches a definition, and that the definition file is included by the Cucumber command or configuration. Check the feature and support-code paths.

  • this.page is undefined: confirm the Before hook ran successfully and assigned the page on the World. If the step accesses this, use a regular function rather than an arrow function.

  • Browser executable is missing: install the browser binary for the Playwright package in use with npx playwright install chromium (or the browser you selected), and run installation in the environment that executes the tests.

  • A step finishes before navigation or an assertion: make the step async and await Playwright operations, or return the promise. Do not start browser work without returning or awaiting it.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Scenarios interfere with one another: keep page, context, and other mutable scenario data on the World; create isolated contexts and avoid sharing a page across concurrent scenarios.

  • Parallel runs exhaust resources or collide on test data: reduce Cucumber parallelism, reuse a browser per worker while keeping contexts scenario-scoped, and make shared accounts or fixtures concurrency-safe.

  • Cleanup is skipped after a failed scenario: put disposal in an After hook and guard cleanup for resources that may not have been created. Check that tag filters do not unintentionally exclude the cleanup hook.

Or skip the browser setup

If your immediate need is a clean website capture rather than an interactive Cucumber scenario, ScreenshotNeo offers a screenshot API and MCP server for developers. One GET request can return an image or PDF:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

See the ScreenshotNeo API documentation for request options. ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo free to try 1,000 screenshots a month with no card.

Frequently Asked Questions

Can I use Playwright Test to run Cucumber feature files?

No. Cucumber.js and Playwright Test are separate runners; in this setup Cucumber.js runs the features and the step definitions call Playwright.

Can Cucumber and Playwright be used with TypeScript?

Yes. Configure Cucumber.js to load TypeScript support code or compile it before running; the example uses JavaScript for a minimal setup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.