### Install browserstack-node-sdk Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-browserstack.md Install the BrowserStack Node.js SDK as a development dependency. ```bash npm i -D browserstack-node-sdk ``` -------------------------------- ### Install Playwright Browsers with Yarn Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/installation.md After installing Playwright, run this command to install the necessary browser binaries using Yarn. ```bash yarn playwright install ``` -------------------------------- ### Install saucectl CLI Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-saucelabs.md Install the saucectl command-line interface globally using npm. ```bash npm install -g saucectl ``` -------------------------------- ### Install Playwright Browsers with Npm Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/installation.md After installing Playwright, run this command to install the necessary browser binaries. ```bash npx playwright install ``` -------------------------------- ### Setup Project for Saving Storage State Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/authentication.md Implement a setup file to authenticate a user and save the storage state to a file. This is used by the static authentication approach. ```typescript // features/auth/setup.ts import { test as setup, expect } from '@playwright/test'; import { AUTH_FILE } from '../../playwright.config'; setup('authenticate', async ({ page }) => { await page.goto('https://example.com/login'); await page.getByLabel('Email').fill('user@example.com'); await page.getByLabel('Password').fill('password'); await page.getByRole('button', { name: 'Log In' }).click(); await expect(page.getByRole('link', { name: 'Sign Out' })).toBeVisible(); await page.context().storageState({ path: AUTH_FILE }); }); ``` -------------------------------- ### Install Playwright Browsers with Pnpm Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/installation.md After installing Playwright, run this command to install the necessary browser binaries using Pnpm. ```bash pnpm playwright install ``` -------------------------------- ### Example: Running a subset of features with featuresRoot Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/configuration/options.md Demonstrates how to specify a subset of features to run when using the featuresRoot option. ```javascript const testDir = defineBddConfig({ featuresRoot: './features', features: './features/game/**/*.feature', // <- run only these features }); ``` -------------------------------- ### Example Feature File Source: https://github.com/vitalets/playwright-bdd/blob/main/skills/playwright-bdd/SKILL.md A sample Gherkin feature file demonstrating a shopping cart scenario. ```gherkin Feature: Shopping cart Scenario: Add item to cart Given I am on a product page And the cart is empty When I add the product "banana" to the cart Then the cart contains "banana" And the cart badge shows 1 ``` -------------------------------- ### Create Cucumber-style steps with createBdd Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/migration-v7.md Since v7, Given/When/Then functions for cucumber-style steps must be created using createBdd, similar to Playwright-style steps. This example shows the basic setup for fixtures. ```typescript import { test as base, createBdd } from 'playwright-bdd'; // define simplest world (see the next section for more details) type World = { page: Page }; export const test = base.extend<{ world: World }>({ world: async ({ page }, use) => { const world = { page }; await use(world); }, }); export const { Given, When, Then } = createBdd(test, { worldFixture: 'world' }); ``` ```typescript import { Given, When, Then } from './fixtures'; Given('I am on home page', async function () { await this.page.goto('/'); }); ``` -------------------------------- ### Simplest World Setup with Page Fixture Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/cucumber-style.md Create the simplest possible World by defining it as a plain object containing only the `page` fixture. This is suitable for minimal test setups. ```javascript import { test as base } from 'playwright-bdd'; export const test = base.extend({ world: async ({ page }, use) => { const world = { page }; await use(world); }, }); export const { Given, When, Then, Before, After } = createBdd(test, { worldFixture: 'world' }); ``` -------------------------------- ### Example: featuresRoot configuration before v8 Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/configuration/options.md Illustrates the configuration of features and steps using explicit paths before Playwright-BDD v8. ```javascript const testDir = defineBddConfig({ features: './features/**/*.feature', steps: './features/steps/**/*.js', featuresRoot: './features', }); ``` -------------------------------- ### Install TestDino Reporter and dotenv Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-testdino.md Install the necessary npm packages for TestDino reporting and environment variable management. ```sh npm i -D @testdino/playwright ``` ```sh npm i -D dotenv ``` -------------------------------- ### Gherkin Feature File Example Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/pickles.md This is an example of a Gherkin feature file that includes a background, a scenario, and a scenario outline with examples. It serves as the basis for understanding pickle generation. ```gherkin Feature: feature 1 Background: A Scenario: scenario 1 B Scenario Outline: scenario 2 C Examples: C1 C2 ``` -------------------------------- ### Start HTTP Server for Cucumber Report Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/reporters/cucumber.md Command to start an HTTP server for serving the generated Cucumber report locally, enabling trace viewer functionality. ```bash npx http-server ./cucumber-report -c-1 -a localhost -o index.html ``` -------------------------------- ### Example Project Structure with Scoped Steps Source: https://github.com/vitalets/playwright-bdd/blob/main/skills/playwright-bdd/SKILL.md Organize your feature files and step definitions into domain-specific directories prefixed with '@' to enable automatic scoping. ```tree features/ ├── fixtures.ts ├── @homepage/ │ ├── homepage.feature │ └── steps.ts ├── @profile/ │ ├── profile.feature │ └── steps.ts └── shared-steps.ts ``` -------------------------------- ### Install Playwright and Playwright-BDD with Npm Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/installation.md Use this command to install both Playwright and Playwright-BDD in a new project or an existing project without Playwright. ```bash npm i -D @playwright/test playwright-bdd ``` -------------------------------- ### Install Playwright and Playwright-BDD with Pnpm Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/installation.md Use this command to install both Playwright and Playwright-BDD in a new project or an existing project without Playwright using Pnpm. ```bash pnpm i -D @playwright/test playwright-bdd ``` -------------------------------- ### Install cross-env Package Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/env-variables.md Install the `cross-env` package as a development dependency to manage environment variables across different platforms. ```bash npm install -D cross-env ``` -------------------------------- ### Example: featuresRoot configuration since v8 Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/configuration/options.md Shows a more concise configuration since Playwright-BDD v8, where featuresRoot can serve as a default for features and steps. ```javascript const testDir = defineBddConfig({ featuresRoot: './features', }); ``` -------------------------------- ### Sample Feature File Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-features/index.md An example of a feature file written in Gherkin syntax, including tags and steps. ```gherkin @desktop Feature: Playwright site @jira:123 Scenario: Check title Given I open url "https://playwright.dev" When I click link "Get started" Then I see in title "Playwright" ``` -------------------------------- ### Install Playwright and Playwright-BDD with Yarn Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/installation.md Use this command to install both Playwright and Playwright-BDD in a new project or an existing project without Playwright using Yarn. ```bash yarn add -D @playwright/test playwright-bdd ``` -------------------------------- ### Install Playwright-BDD with Npm (Existing Playwright Project) Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/installation.md If you already have Playwright installed, use this command to add only Playwright-BDD. ```bash npm i -D playwright-bdd ``` -------------------------------- ### Example Step Definitions in TypeScript Source: https://github.com/vitalets/playwright-bdd/blob/main/skills/playwright-bdd/SKILL.md Implement step definitions using TypeScript, importing necessary functions from './fixtures'. Ensure correct page navigation and element interactions. ```typescript import { Given, When, Then } from './fixtures'; Given('I am on a product page', async ({ page }) => { await page.goto('/product'); }); When('I add the product {string} to the cart', async ({ page }, name: string) => { await page.getByRole('button', { name: `Add ${name}` }).click(); }); Then('the cart badge should show {int}', async ({ page }, count: number) => { await expect(page.locator('.cart-badge')).toHaveText(String(count)); }); ``` -------------------------------- ### Install Currents Playwright Reporter and Dotenv Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-currents.md Install the necessary npm packages for integrating Currents with Playwright and managing environment variables. ```sh npm i -D @currents/playwright ``` ```sh npm i -D dotenv ``` -------------------------------- ### Install Playwright-BDD with Pnpm (Existing Playwright Project) Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/installation.md If you already have Playwright installed, use this command to add only Playwright-BDD using Pnpm. ```bash pnpm i -D playwright-bdd ``` -------------------------------- ### Gherkin with Examples Name as Template Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-features/customize-examples-title.md This Gherkin feature demonstrates using a name for the `Examples:` block that includes column names. This name serves as a template for generated test titles, offering more granular control over titles per Examples block. ```gherkin Feature: Calculator Scenario Outline: Multiply by two Given value is When multiply by two Then result is Examples: positive value | value | result | | 1 | 2 | | 2 | 4 | Examples: negative value | value | result | | -1 | -2 | | -2 | -4 | ``` -------------------------------- ### Install Playwright-BDD with Yarn (Existing Playwright Project) Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/installation.md If you already have Playwright installed, use this command to add only Playwright-BDD using Yarn. ```bash yarn add -D playwright-bdd ``` -------------------------------- ### Omit importTestFrom (Before v7) Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/migration-v7.md Example of configuring `importTestFrom` to specify the fixture file. ```typescript const testDir = defineBddConfig({ importTestFrom: 'steps/fixtures.ts', steps: ['steps/steps.ts'], }); ``` -------------------------------- ### Feature File Example with Serial Mode Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/passing-data-between-scenarios.md Demonstrates a feature file using '@mode:serial' to define scenarios that share state. The 'Authenticate' scenario logs in, and the 'Check profile' scenario uses the same page context. ```gherkin @mode:serial Feature: My feature Scenario: Authenticate Given I am logged in as "user1" Scenario: Check profile # still in the same page with the same context! When I open profile page Then I see name "user1" ``` -------------------------------- ### Generated Pickles from Gherkin Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/pickles.md This shows the 3 pickles generated from the example Gherkin feature file, including their associated steps and references to AST node IDs. It highlights how scenarios and scenario outlines with examples produce multiple pickles. ```text pickle 1 (scenario 1) pickleStep 1.1 (A) pickleStep 1.2 (B) pickle 2 (scenario 2, example row 1) pickleStep 2.1 (A) pickleStep 2.2 (C) pickle 3 (scenario 2, example row 2) pickleStep 3.1 (A) pickleStep 3.2 (C) ``` -------------------------------- ### Example Missing Step Definitions Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/snippets.md This snippet shows the format of generated code for missing steps. Each snippet includes the step signature and a placeholder for the implementation, along with comments indicating the source of the step. ```javascript Given('I open url {string}', async ({}, arg) => { // Step: Given I open url "https://playwright.dev" // From: features/homepage.feature:4:5 }); ``` ```javascript When('I click link {string}', async ({}, arg) => { // Step: When I click link "Get started" // From: features/homepage.feature:5:5 }); ``` ```javascript Then('I see in title {string}', async ({}, arg) => { // Step: Then I see in title "Playwright" // From: features/homepage.feature:6:5 }); ``` -------------------------------- ### Filled ChatGPT Prompt for Todo App Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-features/chatgpt.md An example of a filled prompt for ChatGPT, including a user story and the extracted step definitions for the Todo App. ```text Generate BDD scenarios for the following user story: As a user I want to add and remove todo items in todo list app. Format output as a single gherkin file. Include user story text in the file. Use Background for common steps. Use "And" keyword for repeated "Given" / "When" / "Then". Strictly use only the following step definitions: * Given I am on todo page * When I add todo {string} * When I remove todo {string} * Then visible todos count is {int} ``` -------------------------------- ### Playwright-Style Snippet Example Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/migration-v7.md An example of a missing step definition snippet generated by Playwright-BDD, showing the expected syntax for Playwright-style steps. ```typescript Some steps are without definition! // 1. Missing step definition for "features/one.feature:23:5" Then('I see in title {string}', async ({}, arg: string) => { // ... }); Missing step definitions: 1. Use snippets above to create them. ``` -------------------------------- ### BDD Feature File Example Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/index.md An example of a BDD feature file written in Gherkin syntax, defining a scenario for testing the Playwright home page. ```gherkin Feature: Playwright Home Page Scenario: Check title Given I am on Playwright home page When I click link "Get started" Then I see in title "Installation" ``` -------------------------------- ### Playwright Config with Multiple Projects Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/reporters/cucumber.md Example configuration for playwright.config.ts demonstrating multiple projects and setting up the cucumberReporter. ```typescript import { defineConfig, devices } from '@playwright/test'; import { defineBddConfig, cucumberReporter } from 'playwright-bdd'; const testDir = defineBddConfig({ features: 'features/**/*.feature', steps: 'features/steps/**/*.ts', }); export default defineConfig({ testDir, reporter: [ cucumberReporter('html', { outputFile: 'cucumber-report/index.html' }) ], projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] }, }, { name: 'firefox', use: { ...devices['Desktop Firefox'] }, }, ], }); ``` -------------------------------- ### Test Run Output Source: https://github.com/vitalets/playwright-bdd/blob/main/examples/basic-cjs/README.md Example output after running tests, indicating the number of tests run and their status. ```text Running 2 tests using 1 worker 2 passed (2.9s) ``` -------------------------------- ### Scoping a Step Definition with Tags Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/scoped.md This example shows how to scope a specific step definition to features or scenarios tagged with '@foo'. This is useful when the same step text needs different implementations in different contexts. ```javascript Given('a step', { tags: '@foo' }, async () => { // ... }); ``` -------------------------------- ### Gherkin Feature with Doc String Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/doc-strings.md Example of a Gherkin feature file using a multi-line doc string for a 'When' step. ```gherkin Feature: Some feature Scenario: Use multi-line doc string When Fill "textarea" with: """ This is an example of a doc string. Doc strings can span multiple lines, and all spacing preceding each line that also precedes the block is removed. """ ``` -------------------------------- ### Example Usage in Gherkin Source: https://github.com/vitalets/playwright-bdd/blob/main/examples/auth-in-steps/README.md This snippet shows the Gherkin syntax for logging in a user dynamically within a BDD step. It's used to trigger the authentication logic. ```gherkin Given I am logged in as "xxx@example.com" ``` -------------------------------- ### Define a Basic BeforeScenario Hook Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/hooks/scenario-hooks.md An example of defining a BeforeScenario hook that runs before each scenario. It imports the BeforeScenario function and provides an async callback. ```typescript import { BeforeScenario } from './fixtures'; BeforeScenario(async () => { // runs before each scenario }); ``` -------------------------------- ### BeforeStep Hook with Default Tags Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/hooks/step-hooks.md This example shows how to set default tags for all hooks when creating the BDD instance. The BeforeStep hook will then only run for scenarios matching these default tags. ```typescript const { BeforeStep } = createBdd(test, { tags: '@mobile' }); BeforeStep(async () => { // runs only for scenarios with @mobile }); ``` -------------------------------- ### Install Playwright-BDD Agent Skill Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/agent-skill.md Run this command to add the agent skill to your project. This enables AI coding agents to generate BDD artifacts. ```bash npx skills add vitalets/playwright-bdd ``` -------------------------------- ### Define Custom Fixture for BeforeScenario Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/hooks/scenario-hooks.md Example of defining a custom fixture 'myFixture' that can be used within BeforeScenario hooks. This allows hooks to access and utilize custom test setup. ```typescript import { test as base, createBdd } from 'playwright-bdd'; export const test = base.extend<{ myFixture: MyFixture }>({ myFixture: async ({ page }, use) => { // ... } }); export const { BeforeScenario } = createBdd(test); ``` -------------------------------- ### AfterStep Hook for Screenshot Capture Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/hooks/step-hooks.md This example demonstrates using AfterStep to capture a screenshot after each step. It utilizes the page and $testInfo fixtures to attach the screenshot. ```typescript import { AfterStep } from './fixtures'; AfterStep(async ({ page, $testInfo, $step }) => { await $testInfo.attach(`screenshot after ${$step.title}`, { contentType: 'image/png', body: await page.screenshot(), }); }); ``` -------------------------------- ### Directory Structure for Automatic Tagging Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-features/tags-from-path.md Demonstrates how '@'-prefixed directories automatically assign tags to all features and steps within them. For example, the '@game' directory tags all its contents with '@game'. ```directory features ├── @game <- │ ├── game.feature │ └── steps.ts └── @video-player <- ├── video-player.feature └── steps.ts ``` -------------------------------- ### Initialize Component Testing Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/component-tests.md Use this command to set up component testing for your project. ```bash npm init playwright@latest -- --ct ``` -------------------------------- ### Dynamic Authentication Scenarios Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/authentication.md Example Gherkin scenarios demonstrating dynamic authentication. Different users ('admin', 'user1') are logged in within BDD steps to test role-specific access. ```gherkin Scenario: Admin sees the dashboard Given I am logged in as "admin" When I navigate to the dashboard Then I see the admin panel Scenario: Regular user sees limited menu Given I am logged in as "user1" When I navigate to the dashboard Then I do not see the admin panel ``` -------------------------------- ### Custom Fixture Setup for Scenario Context Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/passing-data-between-scenarios.md Sets up custom 'ctx' and 'ctxMap' fixtures for Playwright BDD. 'ctx' provides a file-specific context shared across scenarios, while 'ctxMap' manages contexts for all files within a worker, ensuring proper cleanup. ```typescript import { test as base, createBdd } from 'playwright-bdd'; // context shared between scenarios in a file type Ctx = { page: Page }; export const test = base.extend<{ ctx: Ctx }, { ctxMap: Record }>({ ctx: async ({ ctxMap }, use, testInfo) => { // get or init a context for the current file ctxMap[testInfo.file] = ctxMap[testInfo.file] || {}; // pass context to scenarios as a `ctx` fixture await use(ctxMap[testInfo.file]); }, ctxMap: [async ({}, use) => { const ctxMap: Record = {}; await use(ctxMap); // cleanup all contexts on worker teardown for (const ctx of Object.values(ctxMap)) await ctx.page?.close(); }, { scope: 'worker' }], }); export const { Given, When, Then } = createBdd(test); ``` -------------------------------- ### Mapping Pickles Back to Gherkin Feature File Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/pickles.md This section maps the generated pickles and their steps back to the original Gherkin feature file. It clarifies which parts of the feature file (Background, Scenario, Scenario Outline, Examples) are referenced by each pickle and step. ```gherkin Feature: feature 1 Background: # referenced from: none A # referenced from: pickleStep 1.1, pickleStep 2.1, pickleStep 3.1 Scenario: scenario 1 # referenced from: pickle 1 B # referenced from: pickleStep 1.2 Scenario Outline: scenario 2 # referenced from: pickle 2, pickle 3 C # referenced from: pickleStep 2.2, pickleStep 3.2 Examples: C1 # referenced from: pickle 2 C2 # referenced from: pickle 3 ``` -------------------------------- ### Show CLI Help Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/cli.md Displays help information for the `bddgen test` command or global help for `bddgen` using the `-h` option. ```bash npx bddgen test -h ``` ```bash npx bddgen -h ``` -------------------------------- ### Configure Steps Option (Before v7) Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/migration-v7.md Illustrates the previous method of specifying step definition files using the `require` or `import` options. ```typescript const testDir = defineBddConfig({ require: ['steps/*.ts'], // or for ESM // import: ['steps/*.ts'], }); ``` -------------------------------- ### Generated Playwright Test Titles from Examples Name Template Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-features/customize-examples-title.md This JavaScript code illustrates the resulting Playwright test titles when using the `Examples:` block name as a template. Each test title is substituted with the corresponding example values, providing clear and specific test identifiers. ```javascript test(`positive value 1`, async ({ Given, When, Then }) => { /* ... */ }); test(`positive value 2`, async ({ Given, When, Then }) => { /* ... */ }); test(`negative value -1`, async ({ Given, When, Then }) => { /* ... */ }); test(`negative value -2`, async ({ Given, When, Then }) => { /* ... */ }); ``` -------------------------------- ### Configure Currents Credentials in .env Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-currents.md Set up your Currents record key and project ID in the .env file for authentication and project identification. ```env CURRENTS_RECORD_KEY=YOUR_RECORD_KEY CURRENTS_PROJECT_ID=YOUR_PROJECT_ID ``` -------------------------------- ### Simplify Configuration with featuresRoot Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/blog/whats-new-in-v8.md Before v8, features and steps required explicit paths. Now, `featuresRoot` serves as a default directory, simplifying configuration for typical projects. ```typescript // before const testDir = defineBddConfig({ features: './features/**/*.feature', steps: './features/steps/**/*.js', featuresRoot: './features', }); // after const testDir = defineBddConfig({ featuresRoot: './features', }); ``` -------------------------------- ### Configure TestDino API Token in .env Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-testdino.md Set up your TestDino API token in a local .env file for secure credential management. ```bash TESTDINO_TOKEN=your_api_key_here ``` -------------------------------- ### Configure Sauce Labs Credentials Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-saucelabs.md Run the saucectl configure command to set up your Sauce Labs username and access key. ```bash saucectl configure ``` -------------------------------- ### Sample Feature File (sample.feature) Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/getting-started/write-first-test.md Defines a test scenario using Gherkin syntax. This file outlines the user's interaction and expected outcomes. ```gherkin Feature: Playwright site Scenario: Check get started link Given I am on home page When I click link "Get started" Then I see in title "Installation" ``` -------------------------------- ### Generated Playwright Test File from Scenario Name Template Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-features/customize-examples-title.md This JavaScript code shows the Playwright test file generated from the Gherkin feature above. Each example row is converted into a test with a title dynamically created using the scenario name template and example values. ```javascript test.describe(`Calculator`, () => { test.describe(`Multiply by two`, () => { test(`Multiply 1 by two`, async ({ Given, When, Then }) => { await Given(`value is 1`); await When(`multiply by two`); await Then(`result is 2`); }); test(`Multiply 2 by two`, async ({ Given, When, Then }) => { await Given(`value is 2`); await When(`multiply by two`); await Then(`result is 4`); }); }); }); ``` -------------------------------- ### Update Playwright-BDD Packages Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/migration-v7.md Remove the old Cucumber dependency and install the latest version of playwright-bdd. ```bash npm un @cucumber/cucumber npm i -D playwright-bdd@latest ``` -------------------------------- ### Worker-scoped After Hook Example Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/api.md Use AfterWorker to run a hook once in each worker after all scenarios. It can be targeted using tags. ```typescript import { AfterWorker } from 'playwright-bdd'; AfterWorker(async ({ $workerInfo }) => { console.log(`Worker finished: ${$workerInfo.workerIndex}`); }); AfterWorker('cleanup', async () => { // This hook runs only for features with tag '@cleanup' }); ``` -------------------------------- ### Simplified Project Configuration with `defineBddProject` Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/configuration/multiple-projects.md Use the `defineBddProject` helper function for a more concise way to configure projects with different feature files. It automatically sets `outputDir` based on the project name. ```typescript import { defineConfig } from '@playwright/test'; import { defineBddProject } from 'playwright-bdd'; export default defineConfig({ projects: [ { ...defineBddProject({ name: 'project-one', features: 'project-one/**/*.feature', steps: 'project-one/steps/**/*.ts', }), }, { ...defineBddProject({ name: 'project-two', features: 'project-two/**/*.feature', steps: 'project-two/steps/**/*.ts', }), }, ], }); ``` -------------------------------- ### Worker-scoped Before Hook Example Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/api.md Use BeforeWorker to run a hook once in each worker before all scenarios. It can be targeted using tags. ```typescript import { BeforeWorker } from 'playwright-bdd'; BeforeWorker(async ({ $workerInfo }) => { console.log(`Running in worker: ${$workerInfo.workerIndex}`); }); BeforeWorker('web', async () => { // This hook runs only for features with tag '@web' }); ``` -------------------------------- ### BrowserStack Project and Browser Configuration Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-browserstack.md Configure project metadata, build information, and the browsers to be used for testing within the `browserstack.yml` file. ```yaml userName: YOUR_USERNAME accessKey: YOUR_ACCESS_KEY projectName: playwright-bdd sample buildName: my-build-name buildIdentifier: '#${BUILD_NUMBER}' platforms: - os: Windows osVersion: 11 browserName: chrome browserVersion: latest playwrightConfigOptions: name: chromium - os: OS X osVersion: Ventura browserName: playwright-webkit browserVersion: latest playwrightConfigOptions: name: osx # more browsers ``` -------------------------------- ### BrowserStack Credentials Configuration Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-browserstack.md Set up your BrowserStack username and access key in the `browserstack.yml` file located in the project root. ```yaml userName: YOUR_USERNAME accessKey: YOUR_ACCESS_KEY ``` -------------------------------- ### Automatic Tagging from Directory Structure Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/blog/whats-new-in-v8.md Demonstrates how directory and file names prefixed with '@' can automatically apply tags to features and steps. This reduces manual tagging efforts and helps associate features with their corresponding steps. ```directory structure features ├── @game <- sets @game tag to all files inside │ ├── game.feature │ └── steps.ts └── @video-player <- sets @video-player tag to all files inside ├── video-player.feature └── steps.ts ``` -------------------------------- ### Gherkin Feature with DataTable Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/data-tables.md Example of a Gherkin feature file using a DataTable to provide structured input for a scenario. ```gherkin Feature: Some feature Scenario: Login When I fill login form with values | label | value | | Username | vitalets | | Password | 12345 | ``` -------------------------------- ### Update Playwright-BDD Package Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/blog/whats-new-in-v8.md Install the latest version of playwright-bdd using npm. This command updates the package to the newest release. ```bash npm install -D playwright-bdd@latest ``` -------------------------------- ### Prettier Configuration for Gherkin Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-features/auto-formatting.md Sample Prettier configuration file to enable the prettier-plugin-gherkin. Ensure this file is named `prettier.config.mjs` or similar. ```javascript export default { plugins: ['prettier-plugin-gherkin'], // ...other prettier options }; ``` -------------------------------- ### Add Report Script to package.json Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/reporters/cucumber.md Example of adding a script to package.json to quickly open the Cucumber report using an HTTP server. ```json { "scripts": { "report": "npx http-server ./cucumber-report -c-1 -a localhost -o index.html" } } ``` -------------------------------- ### Using 'ctx' Fixture to Pass Data Between Steps Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/passing-data-between-steps.md Demonstrates how to use the 'ctx' fixture to store data (like a page event promise) in one step and retrieve it in another. This allows for stateful interactions across steps. ```javascript import { Given, When, Then } from './fixtures'; When('I click the link', async ({ page, ctx }) => { ctx.newTapPromise = context.waitForEvent('page'); await page.getByRole('link').click(); }); Then('new tab is opened', async ({ ctx }) => { const newTab = await ctx.newTapPromise; await expect(newTab).toHaveTitle(/.*checkout/); }); ``` -------------------------------- ### Defining a custom worker fixture Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/hooks/worker-hooks.md Define a custom fixture with 'worker' scope in your test setup. This fixture can then be used in worker hooks. ```typescript import { test as base, createBdd } from 'playwright-bdd'; export const test = base.extend<{}, { myWorkerFixture: MyWorkerFixture }>({ myWorkerFixture: [async ({}, use) => { // ... setup myWorkerFixture }, { scope: 'worker' }] }); export const { BeforeWorker } = createBdd(test); ``` -------------------------------- ### Setting Default Tags with createBdd() Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/scoped.md This shows how to apply default tags to all step definitions and hooks within a file by configuring the `createBdd()` function. This simplifies scoping when all steps in a file belong to the same feature context. ```typescript // game.steps.ts const { Given, When, Then } = createBdd(test, { tags: '@game' }); When('I click the PLAY button', async () => { // actions for game.feature }); ``` ```typescript // video-player.steps.ts const { Given, When, Then } = createBdd(test, { tags: '@video-player' }); When('I click the PLAY button', async () => { // actions for video-player.feature }); ``` -------------------------------- ### Configure Steps Option (Since v7) Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/migration-v7.md Demonstrates the new `steps` option for defining step definition file patterns in Playwright-BDD v7. ```typescript const testDir = defineBddConfig({ steps: 'steps/**/*.ts' }); ``` -------------------------------- ### ChatGPT Prompt Template for BDD Scenarios Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-features/chatgpt.md A template for prompting ChatGPT to generate Gherkin scenarios based on a user story and provided step definitions. ```text Generate BDD scenarios in Gherkin for the following user story: {user story description} Format output as a single gherkin file. Include user story text in the file. Use Background for common steps. Use "And" keyword for repeated "Given" / "When" / "Then". Strictly use only the following step definitions: {steps list from bddgen export} ``` -------------------------------- ### Gherkin Feature with JSON Doc String Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/doc-strings.md Example of a Gherkin feature file using a doc string annotated with the 'json' media type. ```gherkin Feature: Another feature Scenario: Use JSON doc string When Fill page with: """json { "username": "vitalets", "password": "12345" } """ ``` -------------------------------- ### Custom Cucumber Formatter Example Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/reporters/cucumber.md Defines a custom Cucumber formatter that logs envelopes to the console. This is useful for debugging or custom report generation. ```typescript import * as messages from '@cucumber/messages'; import { Formatter, IFormatterOptions } from '@cucumber/cucumber'; export default class CustomFormatter extends Formatter { constructor(options: IFormatterOptions) { super(options); options.eventBroadcaster.on('envelope', (envelope: messages.Envelope) => { console.log(JSON.stringify(envelope)); }); } } ``` -------------------------------- ### Configure npm Scripts for Watching and UI Mode Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/ui-mode.md Set up npm scripts to watch for BDD changes, run Playwright in UI Mode, and combine them using npm-run-all. ```json "scripts": { "watch:bdd": "npx nodemon -w ./features -e feature,js,ts --exec \"npx bddgen\"", "watch:pw": "npx playwright test --ui", "watch": "run-p watch:*" } ``` -------------------------------- ### Define Custom Parameter Type Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/migration-v7.md Example of defining a custom parameter type using `defineParameterType` imported from `playwright-bdd`, compatible with decorator steps. ```typescript import { defineParameterType } from 'playwright-bdd'; type Color = 'red' | 'blue' | 'yellow'; defineParameterType({ name: 'color', regexp: /red|blue|yellow/, transformer: (s) => s.toLowerCase() as Color, }); Given('step with {color}', ({}, color: Color) => { ... }); ``` -------------------------------- ### Using custom worker fixture in BeforeWorker hook Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/hooks/worker-hooks.md Access and utilize custom worker-scoped fixtures within your BeforeWorker hooks for setup operations. ```typescript import { BeforeWorker } from './fixtures'; BeforeWorker(async ({ myWorkerFixture }) => { // ... use myWorkerFixture in hook }); ``` -------------------------------- ### Binding BeforeWorker hook to tags Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/hooks/worker-hooks.md Bind a BeforeWorker hook to specific features using tags. This allows for conditional execution of setup code. ```typescript BeforeWorker({ tags: '@auth' }, async () => { ... }); ``` -------------------------------- ### Todo App Step Definitions Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-features/chatgpt.md Manual step definitions for a Todo App, used as input for ChatGPT. Ensure reliable locators are defined here. ```typescript import { createBdd } from 'playwright-bdd'; const { Given, When, Then } = createBdd(test); Given('I am on todo page', async ({ page }) => { await page.goto('https://demo.playwright.dev/todomvc/'); }); When('I add todo {string}', async ({ page }, text: string) => { await page.locator('input.new-todo').fill(text); await page.locator('input.new-todo').press('Enter'); }); When('I remove todo {string}', async ({ page }, text: string) => { const todo = page.getByTestId('todo-item').filter({ hasText: text }); await todo.hover(); await todo.getByRole('button', { name: 'Delete' }).click(); }); Then('visible todos count is {int}', async ({ page }, count: number) => { await expect(page.getByTestId('todo-item')).toHaveCount(count); }); ``` -------------------------------- ### Export Step Definitions Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/cli.md Prints a list of all found step definitions. This command is useful for generating BDD scenarios with AI tools like ChatGPT. It can optionally output only unused steps using the `--unused-steps` flag. ```bash npx bddgen export ``` -------------------------------- ### Playwright-BDD Step Definitions Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/index.md Example step definitions for Playwright-BDD. These functions are called by the generated tests and have access to Playwright APIs and fixtures like 'page'. ```javascript Given('I am on Playwright home page', async ({ page }) => { await page.goto('https://playwright.dev'); }); When('I click link {string}', async ({ page }, name) => { await page.getByRole('link', { name }).click(); }); Then('I see in title {string}', async ({ page }, text) => { await expect(page).toHaveTitle(new RegExp(text)); }); ``` -------------------------------- ### Check Node.js version Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/migration-v9.md Verify your current Node.js version. The minimum supported version for v9 is 20. ```bash node --version ``` -------------------------------- ### Using $prompt Fixture for Multi-Page Scenarios Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/fix-with-ai.md In multi-page scenarios, use the `$prompt` BDD fixture to manually set the page instance for ARIA snapshot capture. Call `$prompt.setPage(newPage)` to switch the context to the desired page. ```javascript When('I open a new tab', async ({ page, context, $prompt }) => { // <-- add $prompt fixture const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByRole('link').click(), ]); $prompt.setPage(newPage); // <-- call $prompt.setPage() to switch the page await expect(newPage.getByRole('heading')).toContainText('Another page'); }); ``` -------------------------------- ### Configure .env File with dotenv Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/env-vars.md Load environment variables from a .env file into your Playwright configuration by importing 'dotenv/config' in playwright.config.ts. Ensure the dotenv package is installed. ```dotenv # .env USERNAME=foo PASSWORD=bar ``` ```typescript // playwright.config.ts import { defineConfig, devices } from '@playwright/test'; import { defineBddConfig, cucumberReporter } from 'playwright-bdd'; import 'dotenv/config'; // <-- populate env variables from .env const testDir = defineBddConfig({ // ... }); export default defineConfig({ // ... }); ``` -------------------------------- ### Display Environment Information Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/cli.md Displays information about the current Playwright-BDD environment, including platform, Node.js version, and versions of installed Playwright-BDD, Playwright Test, and Cucumber.js packages. ```bash npx bddgen env ``` -------------------------------- ### Configure Playwright with Currents Reporter Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-currents.md Set up the Playwright configuration file to use the Currents reporter, load environment variables, and define BDD feature and step locations. ```typescript import 'dotenv/config'; import { defineConfig, devices } from '@playwright/test'; import { defineBddConfig } from 'playwright-bdd'; import { CurrentsConfig, currentsReporter } from '@currents/playwright'; const currentsConfig: CurrentsConfig = { recordKey: process.env.CURRENTS_RECORD_KEY || '', projectId: process.env.CURRENTS_PROJECT_ID || '', }; const testDir = defineBddConfig({ features: 'features/**/*.feature', steps: 'features/steps/**/*.ts', }); export default defineConfig({ testDir, reporter: [currentsReporter(currentsConfig)], use: { screenshot: 'on', trace: 'on', }, }); ``` -------------------------------- ### Simplified Project Targets with Nx Target Defaults Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/usage-with-nx.md When using nx.json targetDefaults, project.json targets can be simplified to empty objects, inheriting the shared configuration. ```json { "targets": { "bddgen": {}, "e2e": {} } } ``` -------------------------------- ### Re-using Step Function with Fixtures Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/reusing-step-fn.md Demonstrates how to create a reusable step function that accepts fixtures and then invoke it from another step. This is useful for sharing common actions like creating a todo item. ```typescript import { createBdd } from 'playwright-bdd'; const { When, Then } = createBdd(); /** * Creates a todo item with the given text. * * @param {Object} fixtures - The test fixtures * @param {import('@playwright/test').Page} fixtures.page - Playwright page object * @param {string} text - The text content for the todo item */ const createTodo = When('I create todo {string}', async ({ page }, text: string) => { await page.getByLabel('title').fill(text); await page.getByRole('button').click(); }); When('I create 2 todos {string} and {string}', async ({ page }, text1: string, text2: string) => { await createTodo({ page }, text1); await createTodo({ page }, text2); }); ``` -------------------------------- ### Define and Use AfterScenario Hook Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/hooks/scenario-hooks.md An example of defining an AfterScenario hook that runs after each scenario. It follows a similar pattern to BeforeScenario, importing createBdd and defining an async callback. ```typescript import { test as base, createBdd } from 'playwright-bdd'; export const test = base.extend({ /* ...your fixtures */ }); const { AfterScenario } = createBdd(test); AfterScenario(async () => { // runs after each scenario }); ``` -------------------------------- ### Run Component Tests Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/component-tests.md Execute the component tests using the npm script defined in `package.json`. ```bash npm run test-ct ``` -------------------------------- ### Cucumber Expression Step Pattern Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/playwright-style.md Define steps using Cucumber expressions with typed parameters like {string}. This example shows opening a URL and clicking a link. ```typescript Given('I open url {string}', async ({ page }, url: string) => { await page.goto(url); }); When('I click link {string}', async ({ page }, name: string) => { await page.getByRole('link', { name }).click(); }); ``` -------------------------------- ### TypeScript Type Definition for 'ctx' Fixture Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/passing-data-between-steps.md Provides a TypeScript example for defining a more specific type for the 'ctx' fixture, improving type safety when passing data between steps. ```typescript type Ctx = { newTapPromise: Promise }; export const test = base.extend<{ ctx: Ctx }>({ ctx: async ({}, use) => { const ctx = {} as Ctx; await use(ctx); }, }); export const { Given, When, Then } = createBdd(test); ``` -------------------------------- ### Configure Features Option (Before v7) Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/migration-v7.md Shows the previous configuration for feature file paths using the `paths` option. ```typescript const testDir = defineBddConfig({ paths: ['features/*.feature'], }); ``` -------------------------------- ### Save Auth State for User (Playwright >= 1.59) Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/guides/authentication.md Saves the authentication state for a specific user into a file. This is typically done in a setup project before running main tests. ```typescript // features/auth/setup.ts import { test as setup, expect } from '@playwright/test'; import { AUTH_FILE } from '../../playwright.config'; // run setups in parallel setup.describe.configure({ mode: 'parallel' }); setup('authenticate user1', async ({ page }) => { await authenticate(page, 'user1'); }); setup('authenticate user2', async ({ page }) => { await authenticate(page, 'user2'); }); async function authenticate(page, userName) { // ...perform login for userName... await page.context().storageState({ path: AUTH_FILE.replace('{user}', userName) }); } ``` -------------------------------- ### Missing Step Definition Error with matchKeywords Source: https://github.com/vitalets/playwright-bdd/blob/main/docs/writing-steps/keywords-matching.md Illustrates the error message received when a step definition is missing due to strict keyword matching being enabled. ```text Missing step definitions: 1 When('a step', async ({}) => { // Step: When a step // From: features/homepage.feature:4:5 }); Use snippets above to create missing steps. ```