You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress 10版本中安装Cucumber?求详细分步教程

Cypress 10+ 安装配置 Cucumber 分步指南

1. 安装依赖包

首先安装核心的Cucumber预处理工具和轻量打包器(推荐esbuild,比webpack更快):

npm install --save-dev @badeball/cypress-cucumber-preprocessor @bahmutov/cypress-esbuild-preprocessor
# 若使用Yarn:
# yarn add --dev @badeball/cypress-cucumber-preprocessor @bahmutov/cypress-esbuild-preprocessor

2. 配置 cypress.config.js

Cypress 10+ 用cypress.config.js替代旧版cypress.json作为核心配置文件,修改内容如下:

const { defineConfig } = require("cypress");
const createBundler = require("@bahmutov/cypress-esbuild-preprocessor");
const addCucumberPreprocessorPlugin = require("@badeball/cypress-cucumber-preprocessor").addCucumberPreprocessorPlugin;
const createEsbuildPlugin = require("@badeball/cypress-cucumber-preprocessor/esbuild").createEsbuildPlugin;

module.exports = defineConfig({
  e2e: {
    async setupNodeEvents(on, config) {
      const bundler = createBundler({
        plugins: [createEsbuildPlugin(config)],
      });

      on("file:preprocessor", bundler);
      await addCucumberPreprocessorPlugin(on, config);

      return config;
    },
    // 指定Cucumber特征文件的扫描路径
    specPattern: "cypress/e2e/features/**/*.feature",
    // 可选:自定义测试超时时间(按需调整)
    defaultCommandTimeout: 10000,
  },
});

3. 创建标准目录结构

在Cypress项目下建立Cucumber专用目录:

cypress/
└── e2e/
    ├── features/          # 存放.feature格式的测试用例
    │   └── example.feature
    └── step_definitions/  # 存放对应步骤的实现代码
        └── example.js

4. 编写第一个Cucumber测试用例

在cypress/e2e/features/example.feature中写入示例场景:

Feature: 页面基础验证
  测试页面标题和核心元素

  Scenario: 访问Cypress官网并检查标题
    Given 我打开Cypress官方网站
    When 页面完全加载完成
    Then 页面标题应该包含 "Cypress"

5. 实现步骤定义

在cypress/e2e/step_definitions/example.js中编写对应步骤的逻辑:

import { Given, When, Then } from "@badeball/cypress-cucumber-preprocessor";

Given("我打开Cypress官方网站", () => {
  cy.visit("https://www.cypress.io/");
});

When("页面完全加载完成", () => {
  cy.get("header").should("be.visible"); // 用元素可见性替代硬等待,更可靠
});

Then("页面标题应该包含 {string}", (expectedText) => {
  cy.title().should("include", expectedText);
});

6. 启动测试验证配置

运行命令启动Cypress测试管理器:

npx cypress open

选择E2E测试模式和目标浏览器,即可看到example.feature文件,点击即可运行测试。

常见注意事项

  • 确保依赖版本兼容:@badeball/cypress-cucumber-preprocessor需适配Cypress 10+,建议安装最新稳定版
  • 若需使用Webpack打包,需替换预处理包为@badeball/cypress-cucumber-preprocessor/webpack,并额外配置webpack.config.js
  • 步骤定义可按功能模块拆分目录,避免单个文件过于臃肿

内容的提问来源于stack exchange,提问作者mohammed afreen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:11:13