---
title: Cucumber-JS with Playwright | TestingBot
description: Gherkin does not care what language runs it. This chapter writes a second
  feature, for the Playwright team&#39;s TodoMVC demo, and runs it with…
source_url:
  html: https://testingbot.com/resources/courses/cucumber-bdd/cucumber-js-playwright
  md: https://testingbot.com/resources/courses/cucumber-bdd/cucumber-js-playwright.md
---

Course

[BDD with Cucumber: Gherkin to CI](https://testingbot.com/resources/courses/cucumber-bdd)

Chapter 8 of 12

1. [1 Cucumber BDD Tutorial: From Gherkin to CI](https://testingbot.com/resources/courses/cucumber-bdd)
2. [2 BDD Testing Starts Before the Code: Three Amigos](https://testingbot.com/resources/courses/cucumber-bdd/bdd-collaboration)
3. [3 Writing Good Gherkin: Declarative Scenarios](https://testingbot.com/resources/courses/cucumber-bdd/writing-good-gherkin)
4. [4 Cucumber with Java and Selenium: First Scenario](https://testingbot.com/resources/courses/cucumber-bdd/cucumber-java-selenium)
5. [5 Step Definitions, Cucumber Expressions, Parameter Types](https://testingbot.com/resources/courses/cucumber-bdd/step-definitions)
6. [6 Hooks and Sharing State with PicoContainer](https://testingbot.com/resources/courses/cucumber-bdd/hooks-and-shared-state)
7. [7 Scenario Outlines, Tags and Background](https://testingbot.com/resources/courses/cucumber-bdd/outlines-tags-background)
8. [8 Cucumber-JS with Playwright](https://testingbot.com/resources/courses/cucumber-bdd/cucumber-js-playwright)
9. [9 Parallel Runs, Reports and CI on TestingBot](https://testingbot.com/resources/courses/cucumber-bdd/parallel-reports-ci)
10. [10 Other BDD Frameworks: Behave and Reqnroll](https://testingbot.com/resources/courses/cucumber-bdd/behave-and-reqnroll)
11. [11 BDD Anti-Patterns and How to Fix Them](https://testingbot.com/resources/courses/cucumber-bdd/bdd-anti-patterns)
12. [12 Knowledge check](https://testingbot.com/resources/courses/cucumber-bdd/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 8 of 12 Intermediate 7 min read 2 quick checks Updated Nov 2026 

# Cucumber-JS with Playwright
On this page
1. [Set up the project](https://testingbot.com#set-up-the-project)
2. [Configuration](https://testingbot.com#configuration)
3. [The feature](https://testingbot.com#the-feature)
4. [The World: per-scenario state](https://testingbot.com#the-world-per-scenario-state)
5. [Step definitions](https://testingbot.com#step-definitions)
6. [Run it](https://testingbot.com#run-it)
7. [Selenium instead of Playwright](https://testingbot.com#selenium-instead-of-playwright)

Gherkin does not care what language runs it. This chapter writes a second feature, for the Playwright team's TodoMVC demo, and runs it with **Cucumber-JS** , the official JavaScript implementation, driving the browser with **Playwright**. The concepts from chapters 3 to 6 carry over one to one; what changes is how state is shared (a _World_ object instead of dependency injection) and how the browser is started.

A note on the combination: Playwright has its own test runner, `@playwright/test`, with fixtures, retries, tracing and parallelism built in. Cucumber-JS replaces that runner, so you use the Playwright **library** and build those parts yourself. Choose Cucumber-JS when the Gherkin layer is the point (the business reads and reviews the scenarios). If it is not, the [Playwright course](https://testingbot.com/resources/courses/playwright) with `@playwright/test` is the simpler choice.

## Set up the project[#](https://testingbot.com#set-up-the-project)

```bash
mkdir cucumber-js-playwright && cd cucumber-js-playwright
npm init -y
npm pkg set type=module
npm install --save-dev @cucumber/cucumber@13.3.0 playwright@1.65.0
npx playwright install chromium
```

`type=module` lets every file use `import`. The course pins the versions it was run with; Cucumber-JS 13 supports Node.js 22, 24 and 26 or newer (the course ran on Node.js 22).

```
cucumber.js configuration
features/todo.feature the Gherkin
features/support/world.js World, hooks, browser setup
features/step_definitions/todo.steps.js
```

## Configuration[#](https://testingbot.com#configuration)

`cucumber.js` in the project root holds the default profile:

```javascript
export default {
  paths: ['features/**/*.feature'],
  import: ['features/support/ **/*.js', 'features/step_definitions/** /*.js'],
  format: ['progress', 'html:reports/cucumber.html', 'junit:reports/cucumber.xml'],
};
```

`import` is the ESM equivalent of the glue path; use `require` instead if your project is CommonJS. `format` works like the plugins in the Java runner: `progress` prints a dot per step, and the HTML and JUnit reports land in `reports/`.

## The feature[#](https://testingbot.com#the-feature)

```gherkin
Feature: Keeping a todo list
  People add the things they need to do and tick them off when they are done.

  Scenario: The counter shows what is left to do
    Given my todo list is empty
    When I add "Buy milk" and "Call the bank"
    Then I have 2 items left

  Scenario: Completing a todo
    Given my todo list contains "Buy milk" and "Call the bank"
    When I complete "Buy milk"
    Then I have 1 item left
    And "Buy milk" is shown as done
```

Declarative, one `When` each. This feature uses the first person, which is fine for a single-user app.

## The World: per-scenario state[#](https://testingbot.com#the-world-per-scenario-state)

Cucumber-JS creates a new **World** object for every scenario, and binds `this` in every step definition and hook to it. That is its version of chapter 5's PicoContainer: state shared by all steps of one scenario, and nothing shared between scenarios. You customise it by extending `World` and registering the class with `setWorldConstructor`.

`features/support/world.js`:

```javascript
import { setWorldConstructor, setDefaultTimeout, Before, After, World, Status } from '@cucumber/cucumber';
import { chromium, firefox, webkit } from 'playwright';

setDefaultTimeout(60 * 1000);

const engines = { chrome: chromium, edge: chromium, firefox, safari: webkit };

function testingbotEndpoint(name) {
  const capabilities = {
    browserName: process.env.TB_BROWSER ?? 'chrome',
    browserVersion: 'latest',
    platform: process.env.TB_PLATFORM ?? 'WIN11',
    'tb:options': {
      key: process.env.TB_KEY,
      secret: process.env.TB_SECRET,
      name,
      build: process.env.TB_BUILD ?? 'local',
    },
  };
  return `wss://cloud.testingbot.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`;
}

function executor(action, args) {
  return `testingbot_executor: ${JSON.stringify({ action, arguments: args })}`;
}

class TodoWorld extends World {
  get onTestingBot() {
    return process.env.GRID === 'testingbot';
  }

  async openBrowser(scenarioName) {
    if (this.onTestingBot) {
      const engine = engines[process.env.TB_BROWSER ?? 'chrome'];
      this.browser = await engine.connect(testingbotEndpoint(scenarioName));
    } else {
      this.browser = await chromium.launch();
    }
    this.page = await this.browser.newPage();
  }
}

setWorldConstructor(TodoWorld);

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

After(async function ({ result }) {
  if (!this.browser) return;
  try {
    if (this.onTestingBot) {
      const passed = result?.status === Status.PASSED;
      await this.page.evaluate(() => {}, executor('setSessionStatus', {
        passed,
        reason: result?.message?.slice(0, 200) ?? '',
      }));
    }
  } finally {
    await this.browser.close();
  }
});
```

- **`setDefaultTimeout`** : Cucumber-JS fails any step or hook that takes longer than 5 seconds by default. Starting a remote browser can take longer, so the limit is raised to 60 seconds.
- **Hooks use `function`, not arrow functions.** An arrow function does not get its own `this`, so `this.page` would be undefined. The same applies to step definitions.
- **`pickle.name`** is the scenario name; it names the TestingBot session.
- **Locally** , `chromium.launch()` starts a headless Chromium. **On TestingBot** , `connect()` attaches to a browser in the cloud through the [Playwright endpoint](https://testingbot.com/support/web-automate/playwright). `chrome` and `edge` use the `chromium` engine, `safari` uses `webkit`.
- **Reporting** : the `After` hook receives the scenario's result and sends it with a `testingbot_executor` call, the same `setSessionStatus` action documented for Playwright on TestingBot. The `finally` always closes the browser.

A step is written as `When('I complete {string}', async (title) => { await this.page.click(...) })`. It fails with "Cannot read properties of undefined". Why?

 Arrow functions do not get the World as `this`; use `async function (title)` `{string}` does not work in Cucumber-JS The page has not loaded yet, so it needs a timeout

Cucumber-JS binds the World to `this` for regular functions only. An arrow function captures the `this` of the module, which is undefined in ESM.

## Step definitions[#](https://testingbot.com#step-definitions)

`features/step_definitions/todo.steps.js`:

```javascript
import { Given, When, Then } from '@cucumber/cucumber';
import { expect } from 'playwright/test';

const APP = 'https://demo.playwright.dev/todomvc/';

async function addTodos(page, ...titles) {
  const input = page.getByPlaceholder('What needs to be done?');
  for (const title of titles) {
    await input.fill(title);
    await input.press('Enter');
  }
}

Given('my todo list is empty', async function () {
  await this.page.goto(APP);
  await expect(this.page.getByTestId('todo-item')).toHaveCount(0);
});

Given('my todo list contains {string} and {string}', async function (first, second) {
  await this.page.goto(APP);
  await addTodos(this.page, first, second);
});

When('I add {string} and {string}', async function (first, second) {
  await addTodos(this.page, first, second);
});

When('I complete {string}', async function (title) {
  await this.page.getByTestId('todo-item').filter({ hasText: title })
    .getByRole('checkbox').check();
});

Then('I have {int} item(s) left', async function (count) {
  await expect(this.page.getByTestId('todo-count')).toHaveText(`${count} ${count === 1 ? 'item' : 'items'} left`);
});

Then('{string} is shown as done', async function (title) {
  await expect(this.page.getByTestId('todo-item').filter({ hasText: title })).toHaveClass(/completed/);
});
```

The Cucumber expressions are the same as in Java: `{string}`, `{int}`, and the optional `item(s)`. Two Playwright details make these steps robust:

- **Web-first assertions.** `expect` from `playwright/test` (part of the `playwright` package) retries until the condition holds or times out, so there are no sleeps and no "read the counter too early" races. Plain `assert` on a value you read once would not retry.
- **User-facing locators** : placeholder text, test IDs and roles rather than CSS paths. The [Playwright course](https://testingbot.com/resources/courses/playwright) explains locator choice in detail.

## Run it[#](https://testingbot.com#run-it)

Locally:

```bash
npx cucumber-js
```

```
...........

2 scenarios (2 passed)
11 steps (11 passed)
```

The step count includes the `Before` and `After` hooks, which Cucumber-JS reports as steps. To run on TestingBot, set the environment variables the World reads:

```bash
export TB_KEY=your-key
export TB_SECRET=your-secret
GRID=testingbot TB_BROWSER=chrome TB_PLATFORM=WIN11 TB_BUILD=cucumber-js-course npx cucumber-js
```

When this chapter was run on the grid, the two scenarios became the sessions `4e7fe56c353b-9942dd735c5e-c5976de82ba5-179456362441-07965983` ("The counter shows what is left to do") and `bccfa6bdc0fd-2af03346a810-523f2bb8437e-179456364048-49831641` ("Completing a todo"), both reported as passed (Chrome 156 on Windows 11).

Starting the remote browser in the `Before` hook fails with "function timed out, ensure the promise resolves within 5000 milliseconds". What is the fix?

 Switch from `connect()` to `launch()` Raise the limit with `setDefaultTimeout`, or pass a timeout to that hook Add `await page.waitForTimeout(5000)` to the hook

Cucumber-JS gives every step and hook 5 seconds by default. A cloud browser can take longer to start, so the timeout needs raising; waiting longer inside the hook only makes it time out sooner.

## Selenium instead of Playwright[#](https://testingbot.com#selenium-instead-of-playwright)

If your team already has Selenium page objects in JavaScript, Cucumber-JS works the same way with `selenium-webdriver`: build the driver in the `Before` hook with `new Builder().usingServer('https://hub.testingbot.com/wd/hub')`, keep it on the World, report with `driver.executeScript('tb:test-result=passed')` and quit in `After`. The [Node.js Selenium docs](https://testingbot.com/support/web-automate/selenium/nodejs) show the capabilities.

[Previous · Chapter 7 Scenario Outlines, Tags and Background](https://testingbot.com/resources/courses/cucumber-bdd/outlines-tags-background) [Next · Chapter 9 Parallel Runs, Reports and CI on TestingBot](https://testingbot.com/resources/courses/cucumber-bdd/parallel-reports-ci)

On this page

1. [Set up the project](https://testingbot.com#set-up-the-project)
2. [Configuration](https://testingbot.com#configuration)
3. [The feature](https://testingbot.com#the-feature)
4. [The World: per-scenario state](https://testingbot.com#the-world-per-scenario-state)
5. [Step definitions](https://testingbot.com#step-definitions)
6. [Run it](https://testingbot.com#run-it)
7. [Selenium instead of Playwright](https://testingbot.com#selenium-instead-of-playwright)

Certification

Earn the free, resume-worthy TestingBot Cucumber BDD Certification for this course.

[How it works](https://testingbot.com/resources/courses/cucumber-bdd/certification)
