从零开始使用TypeScript和Cucumber创建一个Cypress项目

2025-08-12   出处: Mediam  作/译者:Pablo Peña/溜的一比

最近,我一直在使用 TypeScript 和 Cucumber 构建一个 Cypress 端到端测试自动化项目。以下是我选择这套技术组合的原因:
Cypress

  • 直接在浏览器中运行,速度快且稳定
  • 安装配置简单
  • 提供交互式调试界面
    TypeScript
  • 强类型检查减少错误
  • 更好的代码可维护性
    Cucumber
  • 通过 .feature 文件实现行为驱动开发(BDD)
  • 非技术人员也能阅读测试用例
    这三个工具的组合能为您的应用构建完整的测试体系,显著提升应用质量。以下是具体实施步骤:

前置条件

  • 已安装 Node.js
  • 已安装 npm

步骤 1:初始化项目

mkdir project-name && cd project-name
npm init -y

步骤 2:安装依赖

# 安装 Cypress
npm install cypress --save-dev

# 安装 TypeScript 支持
npm install typescript @types/node @types/cypress --save-dev

# 安装 Cucumber 预处理器
npm install @badeball/cypress-cucumber-preprocessor --save-dev

步骤 3:配置 TypeScript

在项目根目录创建 tsconfig.json​:

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["es6", "dom"],
    "types": ["cypress", "node"],
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true
  },
  "include": ["cypress/**/*.ts"]
}

步骤 4:配置 Cypress

创建 cypress.config.js​:

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')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      const bundler = createBundler({ plugins: [createEsbuildPlugin(config)] })
      on('file:preprocessor', bundler)
      addCucumberPreprocessorPlugin(on, config)
      return config
    },
    specPattern: 'cypress/integration/**/*.feature',
    baseUrl: 'https://parabank.parasoft.com/parabank'
  }
})

步骤 5:创建项目结构

采用 Page Object Model 模式:

mkdir -p cypress/integration/BDD        # 测试场景和步骤定义
mkdir -p cypress/integration/pageObject # 页面元素定位
mkdir -p cypress/support                # 自定义命令和类型定义

步骤 6:编写测试

Feature 文件 (cypress/integration/BDD/Account.feature)

Feature: 用户账户服务操作

  Scenario: 成功开立新账户
    Given 我已登录ParaBank
    When 我开立储蓄账户
    Then 账户概览页显示新账户
    And 新账户详情显示正确余额

  Scenario: 转账操作
    Given 我已登录ParaBank
    When 从支票账户向储蓄账户转账
    Then 转账成功提示可见

步骤定义 (cypress/integration/BDD/Account/transferFunds.ts)

import { Given, When, Then } from "@badeball/cypress-cucumber-preprocessor"
import HomePage from "../../pageObject/HomePage"
import ProfileMainPage from "../../pageObject/ProfileMainPage"
import TransferFundsPage from "../../pageObject/TransferFundsPage"

const homePage = new HomePage()
const profileMainPage = new ProfileMainPage()
const transferFundsPage = new TransferFundsPage()
const transferAmount = '1.00'

Given('我已登录ParaBank', () => {
  cy.visit(Cypress.env("url") + "/index.htm")
  cy.fixture('users.json').as('users').then((users) => {
    homePage.usernameInput.type(users.correct_user.user_name)
    homePage.passwordInput.type(users.correct_user.password)
    homePage.loginButton.click()
    profileMainPage.welcomeMessage.should('contain', 'Welcome')
  })
})

When('从支票账户向储蓄账户转账', () => {
  homePage.transferLink.click()
  transferFundsPage.amountInput.type(transferAmount)
  transferFundsPage.fromAccountSelect.select('12345')
  transferFundsPage.toAccountSelect.select('54321')
  transferFundsPage.transferButton.click()
})

Then('转账成功提示可见', () => {
  transferFundsPage.transferMessage.should('contain', 'Transfer Complete!')
  transferFundsPage.amountDisplay.should('contain', `$${transferAmount}`)
})

页面对象 (cypress/integration/pageObject/HomePage.ts)

class HomePage {
  usernameInput() { return cy.get('#username') }
  passwordInput() { return cy.get('#password') }
  loginButton() { return cy.get('button[type="submit"]') }
  transferLink() { return cy.get('a[href*="transfer.htm"]') }
}

export default HomePage

数据存储在 cypress/fixtures/users.json​:

{
  "correct_user": {
    "user_name": "testuser",
    "password": "testpass"
  }
}

步骤 7:运行测试

npx cypress open

项目优势

  • 速度与可靠性:Cypress 的浏览器内执行机制
  • 代码质量:TypeScript 的静态类型检查
  • 协作友好:Cucumber 的自然语言测试场景
    这套组合为自动化测试提供了完整解决方案,特别适合需要 BDD 实践的中大型项目。

声明:本文为本站编辑转载,文章版权归原作者所有。文章内容为作者个人观点,本站只提供转载参考(依行业惯例严格标明出处和作译者),目的在于传递更多专业信息,普惠测试相关从业者,开源分享,推动行业交流和进步。 如涉及作品内容、版权和其它问题,请原作者及时与本站联系(QQ:1017718740),我们将第一时间进行处理。本站拥有对此声明的最终解释权!欢迎大家通过新浪微博(@测试窝)或微信公众号(测试窝)关注我们,与我们的编辑和其他窝友交流。
/44 人阅读/0 条评论 发表评论

登录 后发表评论
最新文章