playwright-bdd-gherkin-syntax

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Playwright BDD Gherkin Syntax

Playwright BDD Gherkin 语法

Expert knowledge of Gherkin syntax for writing feature files in Playwright BDD, including scenarios, outlines, backgrounds, tags, and internationalization.
精通用于在Playwright BDD中编写特征文件的Gherkin语法,包括场景、场景大纲、背景、标签和国际化等内容。

Overview

概述

Gherkin is a domain-specific language for describing software behavior in plain text. Playwright BDD uses Gherkin feature files (
.feature
) that are transformed into Playwright test files via
bddgen
.
Gherkin是一种用于以纯文本描述软件行为的领域特定语言。Playwright BDD使用Gherkin特征文件(
.feature
),并通过
bddgen
将其转换为Playwright测试文件。

Feature File Structure

特征文件结构

Basic Structure

基础结构

gherkin
Feature: User Authentication
  As a user
  I want to be able to log in
  So that I can access my account

  Background:
    Given I am on the login page

  Scenario: Successful login
    When I enter valid credentials
    And I click the login button
    Then I should see the dashboard

  Scenario: Failed login
    When I enter invalid credentials
    And I click the login button
    Then I should see an error message
gherkin
Feature: User Authentication
  As a user
  I want to be able to log in
  So that I can access my account

  Background:
    Given I am on the login page

  Scenario: Successful login
    When I enter valid credentials
    And I click the login button
    Then I should see the dashboard

  Scenario: Failed login
    When I enter invalid credentials
    And I click the login button
    Then I should see an error message

Feature Declaration

特征声明

gherkin
Feature: Short descriptive title

  Optional description spanning
  multiple lines explaining the
  feature's purpose and context.
gherkin
Feature: Short descriptive title

  Optional description spanning
  multiple lines explaining the
  feature's purpose and context.

Keywords

关键字

Given - Preconditions

Given - 前置条件

Describes the initial context or state:
gherkin
Given I am logged in as "admin"
Given the shopping cart is empty
Given the following users exist:
  | name  | email           |
  | Alice | alice@test.com  |
  | Bob   | bob@test.com    |
描述初始上下文或状态:
gherkin
Given I am logged in as "admin"
Given the shopping cart is empty
Given the following users exist:
  | name  | email           |
  | Alice | alice@test.com  |
  | Bob   | bob@test.com    |

When - Actions

When - 操作

Describes the action or event:
gherkin
When I click the "Submit" button
When I fill in "email" with "test@example.com"
When I select "Express" from the shipping options
When 24 hours have passed
描述执行的操作或事件:
gherkin
When I click the "Submit" button
When I fill in "email" with "test@example.com"
When I select "Express" from the shipping options
When 24 hours have passed

Then - Outcomes

Then - 预期结果

Describes the expected outcome:
gherkin
Then I should see "Welcome back!"
Then the cart should contain 3 items
Then I should be redirected to the dashboard
Then an email should be sent to "test@example.com"
描述预期的结果:
gherkin
Then I should see "Welcome back!"
Then the cart should contain 3 items
Then I should be redirected to the dashboard
Then an email should be sent to "test@example.com"

And / But - Continuation

And / But - 延续

Continues the previous Given/When/Then:
gherkin
Given I am logged in
And I have items in my cart
But I have not entered a shipping address

When I click checkout
And I enter my payment details

Then I should see the confirmation page
And I should receive an order email
But I should not be charged twice
延续前一个Given/When/Then步骤:
gherkin
Given I am logged in
And I have items in my cart
But I have not entered a shipping address

When I click checkout
And I enter my payment details

Then I should see the confirmation page
And I should receive an order email
But I should not be charged twice

Scenario Types

场景类型

Basic Scenario

基础场景

gherkin
Scenario: Add item to cart
  Given I am on the product page
  When I click "Add to Cart"
  Then the cart count should be 1
gherkin
Scenario: Add item to cart
  Given I am on the product page
  When I click "Add to Cart"
  Then the cart count should be 1

Scenario Outline (Data-Driven)

Scenario Outline(数据驱动)

Run the same scenario with different data:
gherkin
Scenario Outline: Login with different roles
  Given I am on the login page
  When I login as "<role>"
  Then I should see the "<dashboard>" dashboard

  Examples:
    | role    | dashboard |
    | admin   | Admin     |
    | user    | User      |
    | manager | Manager   |
Multiple example tables:
gherkin
Scenario Outline: Product pricing
  Given I am viewing product "<product>"
  Then the price should be "<price>"
  And the discount should be "<discount>"

  Examples: Regular Products
    | product | price  | discount |
    | Laptop  | $999   | 0%       |
    | Mouse   | $29    | 0%       |

  Examples: Sale Products
    | product    | price  | discount |
    | Keyboard   | $79    | 20%      |
    | Headphones | $149   | 15%      |
使用不同数据运行同一个场景:
gherkin
Scenario Outline: Login with different roles
  Given I am on the login page
  When I login as "<role>"
  Then I should see the "<dashboard>" dashboard

  Examples:
    | role    | dashboard |
    | admin   | Admin     |
    | user    | User      |
    | manager | Manager   |
多个示例表格:
gherkin
Scenario Outline: Product pricing
  Given I am viewing product "<product>"
  Then the price should be "<price>"
  And the discount should be "<discount>"

  Examples: Regular Products
    | product | price  | discount |
    | Laptop  | $999   | 0%       |
    | Mouse   | $29    | 0%       |

  Examples: Sale Products
    | product    | price  | discount |
    | Keyboard   | $79    | 20%      |
    | Headphones | $149   | 15%      |

Background (Shared Setup)

Background(共享设置)

Runs before each scenario in the feature:
gherkin
Feature: Shopping Cart

  Background:
    Given I am logged in
    And I have an empty cart

  Scenario: Add single item
    When I add "Product A" to cart
    Then the cart should have 1 item

  Scenario: Add multiple items
    When I add "Product A" to cart
    And I add "Product B" to cart
    Then the cart should have 2 items
在特征中的每个场景运行前执行:
gherkin
Feature: Shopping Cart

  Background:
    Given I am logged in
    And I have an empty cart

  Scenario: Add single item
    When I add "Product A" to cart
    Then the cart should have 1 item

  Scenario: Add multiple items
    When I add "Product A" to cart
    And I add "Product B" to cart
    Then the cart should have 2 items

Rule (Grouping Related Scenarios)

Rule(相关场景分组)

Group scenarios under business rules:
gherkin
Feature: Discount System

  Rule: Bulk discounts apply to orders over 10 items

    Scenario: Order with 10 items gets no discount
      Given I have 10 items in my cart
      Then I should see no discount applied

    Scenario: Order with 11 items gets bulk discount
      Given I have 11 items in my cart
      Then I should see a 10% discount applied

  Rule: VIP members get additional discounts

    Scenario: VIP member gets member discount
      Given I am a VIP member
      When I view my cart
      Then I should see a 5% member discount
将场景归类到业务规则下:
gherkin
Feature: Discount System

  Rule: Bulk discounts apply to orders over 10 items

    Scenario: Order with 10 items gets no discount
      Given I have 10 items in my cart
      Then I should see no discount applied

    Scenario: Order with 11 items gets bulk discount
      Given I have 11 items in my cart
      Then I should see a 10% discount applied

  Rule: VIP members get additional discounts

    Scenario: VIP member gets member discount
      Given I am a VIP member
      When I view my cart
      Then I should see a 5% member discount

Tags

标签

Basic Tags

基础标签

gherkin
@smoke
Feature: User Authentication

  @critical
  Scenario: Successful login
    Given I am on the login page
    When I enter valid credentials
    Then I should see the dashboard

  @regression @slow
  Scenario: Password recovery
    Given I am on the forgot password page
    When I request a password reset
    Then I should receive an email
gherkin
@smoke
Feature: User Authentication

  @critical
  Scenario: Successful login
    Given I am on the login page
    When I enter valid credentials
    Then I should see the dashboard

  @regression @slow
  Scenario: Password recovery
    Given I am on the forgot password page
    When I request a password reset
    Then I should receive an email

Special Playwright BDD Tags

Playwright BDD专属标签

gherkin
undefined
gherkin
undefined

Skip this scenario

跳过该场景

@skip Scenario: Feature not ready Given this is skipped
@skip Scenario: Feature not ready Given this is skipped

Run only this scenario (like test.only)

仅运行该场景(类似test.only)

@only Scenario: Debug this specific test Given I need to focus on this
@only Scenario: Debug this specific test Given I need to focus on this

Mark as known failure

标记为已知失败

@fail Scenario: Known bug #123 Given this is expected to fail
@fail Scenario: Known bug #123 Given this is expected to fail

Mark as flaky but continue

标记为不稳定但继续执行

@fixme Scenario: Intermittently failing test Given this sometimes fails
undefined
@fixme Scenario: Intermittently failing test Given this sometimes fails
undefined

Tag Expressions

标签表达式

Filter tests by tags when running:
bash
undefined
运行测试时通过标签筛选:
bash
undefined

Run only smoke tests

仅运行冒烟测试

npx playwright test --grep @smoke
npx playwright test --grep @smoke

Run critical tests

运行关键测试

npx playwright test --grep @critical
npx playwright test --grep @critical

Run everything except slow tests

运行除慢测试外的所有测试

npx playwright test --grep-invert @slow
npx playwright test --grep-invert @slow

Combine tags (AND)

组合标签(逻辑与)

npx playwright test --grep "@smoke.*@critical"
undefined
npx playwright test --grep "@smoke.*@critical"
undefined

Tag Inheritance

标签继承

Tags on Feature apply to all scenarios:
gherkin
@authentication @web
Feature: User Login

  @happy-path
  Scenario: Successful login
    # Has tags: @authentication, @web, @happy-path
    ...

  @error-handling
  Scenario: Invalid password
    # Has tags: @authentication, @web, @error-handling
    ...
特征上的标签会应用到所有场景:
gherkin
@authentication @web
Feature: User Login

  @happy-path
  Scenario: Successful login
    # 拥有标签:@authentication, @web, @happy-path
    ...

  @error-handling
  Scenario: Invalid password
    # 拥有标签:@authentication, @web, @error-handling
    ...

Data Tables

数据表格

Simple Lists

简单列表

gherkin
Scenario: Add multiple items
  When I add the following items:
    | Milk   |
    | Bread  |
    | Butter |
gherkin
Scenario: Add multiple items
  When I add the following items:
    | Milk   |
    | Bread  |
    | Butter |

Key-Value Tables

键值对表格

gherkin
Scenario: Fill registration form
  When I fill in the form with:
    | First Name | John           |
    | Last Name  | Doe            |
    | Email      | john@test.com  |
    | Password   | secret123      |
gherkin
Scenario: Fill registration form
  When I fill in the form with:
    | First Name | John           |
    | Last Name  | Doe            |
    | Email      | john@test.com  |
    | Password   | secret123      |

Tables with Headers

带表头的表格

gherkin
Scenario: Create multiple users
  Given the following users exist:
    | username | email           | role  |
    | alice    | alice@test.com  | admin |
    | bob      | bob@test.com    | user  |
    | carol    | carol@test.com  | user  |
gherkin
Scenario: Create multiple users
  Given the following users exist:
    | username | email           | role  |
    | alice    | alice@test.com  | admin |
    | bob      | bob@test.com    | user  |
    | carol    | carol@test.com  | user  |

Complex Tables

复杂表格

gherkin
Scenario: Order with multiple products
  When I create an order with:
    | product   | quantity | price | discount |
    | Laptop    | 1        | 999   | 0%       |
    | Mouse     | 2        | 29    | 10%      |
    | Keyboard  | 1        | 79    | 5%       |
  Then the order total should be $1123.55
gherkin
Scenario: Order with multiple products
  When I create an order with:
    | product   | quantity | price | discount |
    | Laptop    | 1        | 999   | 0%       |
    | Mouse     | 2        | 29    | 10%      |
    | Keyboard  | 1        | 79    | 5%       |
  Then the order total should be $1123.55

Doc Strings

文档字符串

Plain Text

纯文本

gherkin
Scenario: Submit feedback
  When I enter the following feedback:
    """
    Great product! Would recommend.
    Fast shipping and excellent quality.
    """
  And I click submit
  Then I should see "Thank you for your feedback"
gherkin
Scenario: Submit feedback
  When I enter the following feedback:
    """
    Great product! Would recommend.
    Fast shipping and excellent quality.
    """
  And I click submit
  Then I should see "Thank you for your feedback"

JSON Content

JSON内容

gherkin
Scenario: Create product via API
  When I send a POST request with:
    """json
    {
      "name": "New Product",
      "price": 49.99,
      "category": "electronics",
      "tags": ["new", "featured"]
    }
    """
  Then the response status should be 201
gherkin
Scenario: Create product via API
  When I send a POST request with:
    """json
    {
      "name": "New Product",
      "price": 49.99,
      "category": "electronics",
      "tags": ["new", "featured"]
    }
    """
  Then the response status should be 201

Code Blocks

代码块

gherkin
Scenario: Execute script
  When I run the following script:
    """javascript
    const result = await page.evaluate(() => {
      return document.title;
    });
    console.log(result);
    """
gherkin
Scenario: Execute script
  When I run the following script:
    """javascript
    const result = await page.evaluate(() => {
      return document.title;
    });
    console.log(result);
    """

Internationalization (i18n)

国际化(i18n)

Language Header

语言头部

gherkin
undefined
gherkin
undefined

language: de

language: de

Funktionalität: Benutzeranmeldung
Grundlage: Angenommen ich bin auf der Anmeldeseite
Szenario: Erfolgreiche Anmeldung Wenn ich gültige Anmeldedaten eingebe Dann sollte ich das Dashboard sehen
undefined
Funktionalität: Benutzeranmeldung
Grundlage: Angenommen ich bin auf der Anmeldeseite
Szenario: Erfolgreiche Anmeldung Wenn ich gültige Anmeldedaten eingebe Dann sollte ich das Dashboard sehen
undefined

Supported Languages

支持的语言

Common languages and their keywords:
German (de):
gherkin
undefined
常见语言及其关键字:
德语(de):
gherkin
undefined

language: de

language: de

Funktionalität: Feature title Szenario: Scenario title Angenommen: Given Wenn: When Dann: Then Und: And Aber: But

**French (fr):**

```gherkin
Funktionalität: Feature title Szenario: Scenario title Angenommen: Given Wenn: When Dann: Then Und: And Aber: But

**法语(fr):**

```gherkin

language: fr

language: fr

Fonctionnalité: Feature title Scénario: Scenario title Soit: Given Quand: When Alors: Then Et: And Mais: But

**Spanish (es):**

```gherkin
Fonctionnalité: Feature title Scénario: Scenario title Soit: Given Quand: When Alors: Then Et: And Mais: But

**西班牙语(es):**

```gherkin

language: es

language: es

Característica: Feature title Escenario: Scenario title Dado: Given Cuando: When Entonces: Then Y: And Pero: But
undefined
Característica: Feature title Escenario: Scenario title Dado: Given Cuando: When Entonces: Then Y: And Pero: But
undefined

Comments

注释

gherkin
Feature: Product Catalog
  # This feature covers the product listing pages

  # TODO: Add search functionality tests
  Scenario: View all products
    Given I am on the catalog page
    # Check that products load
    Then I should see at least 10 products
gherkin
Feature: Product Catalog
  # 该特征覆盖产品列表页面

  # TODO: 添加搜索功能测试
  Scenario: View all products
    Given I am on the catalog page
    # 检查产品是否加载
    Then I should see at least 10 products

Best Practices

最佳实践

Write Declarative Steps

编写声明式步骤

Good (declarative):
gherkin
Given I am logged in as an admin
When I create a new product
Then the product should be visible in the catalog
Bad (imperative):
gherkin
Given I navigate to "/login"
And I type "admin@test.com" in the email field
And I type "password123" in the password field
And I click the login button
And I wait for the dashboard to load
When I click the "Products" menu item
And I click "Add New"
...
推荐(声明式):
gherkin
Given I am logged in as an admin
When I create a new product
Then the product should be visible in the catalog
不推荐(命令式):
gherkin
Given I navigate to "/login"
And I type "admin@test.com" in the email field
And I type "password123" in the password field
And I click the login button
And I wait for the dashboard to load
When I click the "Products" menu item
And I click "Add New"
...

Use Meaningful Scenario Names

使用有意义的场景名称

Good:
gherkin
Scenario: Logged-in user can add items to wishlist
Scenario: Guest users are prompted to register before checkout
Scenario: Expired promo codes show clear error message
Bad:
gherkin
Scenario: Test 1
Scenario: Check wishlist
Scenario: Error test
推荐:
gherkin
Scenario: Logged-in user can add items to wishlist
Scenario: Guest users are prompted to register before checkout
Scenario: Expired promo codes show clear error message
不推荐:
gherkin
Scenario: Test 1
Scenario: Check wishlist
Scenario: Error test

Keep Scenarios Independent

保持场景独立

Each scenario should work in isolation:
gherkin
undefined
每个场景应独立运行:
gherkin
undefined

Good - each scenario sets up its own state

推荐 - 每个场景自行设置状态

Scenario: Edit existing product Given a product "Test Product" exists When I edit the product name to "Updated Product" Then I should see "Updated Product" in the list
Scenario: Edit existing product Given a product "Test Product" exists When I edit the product name to "Updated Product" Then I should see "Updated Product" in the list

Bad - depends on previous scenario

不推荐 - 依赖前一个场景

Scenario: Edit the product

Assumes product from previous scenario exists

When I edit the product name Then it should be updated
undefined
Scenario: Edit the product

假设前一个场景中的产品已存在

When I edit the product name Then it should be updated
undefined

Use Background Wisely

合理使用Background

Only put truly common setup in Background:
gherkin
undefined
仅将真正通用的设置放入Background:
gherkin
undefined

Good - common setup

推荐 - 通用设置

Background: Given I am logged in
Background: Given I am logged in

Bad - too specific

不推荐 - 过于具体

Background: Given I am logged in And I have created a product "Widget" And the product has 5 reviews And the product is on sale
undefined
Background: Given I am logged in And I have created a product "Widget" And the product has 5 reviews And the product is on sale
undefined

Organize with Tags

使用标签组织测试

gherkin
@e2e @checkout
Feature: Checkout Process

  @smoke @critical
  Scenario: Complete checkout with credit card
    ...

  @regression
  Scenario: Checkout with PayPal
    ...

  @slow @integration
  Scenario: Checkout with inventory sync
    ...
gherkin
@e2e @checkout
Feature: Checkout Process

  @smoke @critical
  Scenario: Complete checkout with credit card
    ...

  @regression
  Scenario: Checkout with PayPal
    ...

  @slow @integration
  Scenario: Checkout with inventory sync
    ...

Avoid Too Many Steps

避免过多步骤

Keep scenarios focused (ideally 3-7 steps):
Good:
gherkin
Scenario: Add item to cart
  Given I am viewing a product
  When I click "Add to Cart"
  Then the cart should show 1 item
Bad (too many steps):
gherkin
Scenario: Complete purchase
  Given I am logged in
  And I am on the home page
  And I search for "laptop"
  And I click on the first result
  And I select color "silver"
  And I select memory "16GB"
  And I click add to cart
  And I view my cart
  And I click checkout
  And I enter my address
  And I select shipping method
  And I enter credit card details
  And I confirm the order
  Then I should see order confirmation
  # Too long - break into multiple scenarios
保持场景聚焦(理想情况下3-7个步骤):
推荐:
gherkin
Scenario: Add item to cart
  Given I am viewing a product
  When I click "Add to Cart"
  Then the cart should show 1 item
不推荐(步骤过多):
gherkin
Scenario: Complete purchase
  Given I am logged in
  And I am on the home page
  And I search for "laptop"
  And I click on the first result
  And I select color "silver"
  And I select memory "16GB"
  And I click add to cart
  And I view my cart
  And I click checkout
  And I enter my address
  And I select shipping method
  And I enter credit card details
  And I confirm the order
  Then I should see order confirmation
  # 过长 - 拆分为多个场景

Common Patterns

常见模式

Setup and Verification Pattern

设置与验证模式

gherkin
Scenario: Delete a product
  Given a product "Test Product" exists     # Setup
  When I delete "Test Product"               # Action
  Then "Test Product" should not be visible  # Verification
gherkin
Scenario: Delete a product
  Given a product "Test Product" exists     # 设置
  When I delete "Test Product"               # 操作
  Then "Test Product" should not be visible  # 验证

State Transition Pattern

状态转换模式

gherkin
Scenario: Order lifecycle
  Given an order in "pending" status
  When I process the order
  Then the order status should be "processing"

  When I ship the order
  Then the order status should be "shipped"

  When the order is delivered
  Then the order status should be "completed"
gherkin
Scenario: Order lifecycle
  Given an order in "pending" status
  When I process the order
  Then the order status should be "processing"

  When I ship the order
  Then the order status should be "shipped"

  When the order is delivered
  Then the order status should be "completed"

Error Handling Pattern

错误处理模式

gherkin
@error-handling
Scenario: Invalid form submission
  Given I am on the registration page
  When I submit the form with:
    | email    | invalid-email |
    | password | 123           |
  Then I should see the following errors:
    | field    | message                    |
    | email    | Please enter a valid email |
    | password | Password too short         |
gherkin
@error-handling
Scenario: Invalid form submission
  Given I am on the registration page
  When I submit the form with:
    | email    | invalid-email |
    | password | 123           |
  Then I should see the following errors:
    | field    | message                    |
    | email    | Please enter a valid email |
    | password | Password too short         |

File Organization

文件组织

features/
├── authentication/
│   ├── login.feature
│   ├── logout.feature
│   └── password-reset.feature
├── products/
│   ├── catalog.feature
│   ├── search.feature
│   └── product-details.feature
├── checkout/
│   ├── cart.feature
│   ├── payment.feature
│   └── shipping.feature
└── admin/
    ├── user-management.feature
    └── product-management.feature
features/
├── authentication/
│   ├── login.feature
│   ├── logout.feature
│   └── password-reset.feature
├── products/
│   ├── catalog.feature
│   ├── search.feature
│   └── product-details.feature
├── checkout/
│   ├── cart.feature
│   ├── payment.feature
│   └── shipping.feature
└── admin/
    ├── user-management.feature
    └── product-management.feature

When to Use This Skill

何时使用该技能

  • Writing new feature files
  • Converting requirements to Gherkin scenarios
  • Using Scenario Outline for data-driven tests
  • Organizing tests with tags
  • Setting up shared Background steps
  • Working with internationalized features
  • Reviewing and improving feature file quality
  • Training team members on BDD syntax
  • 编写新的特征文件
  • 将需求转换为Gherkin场景
  • 使用Scenario Outline实现数据驱动测试
  • 使用标签组织测试
  • 设置共享Background步骤
  • 处理国际化特征
  • 评审并优化特征文件质量
  • 培训团队成员掌握BDD语法