DEV Community

Dennis Zhang
Dennis Zhang

Posted on

cypress-cucumber-preprocessor(Gherkin语法)

学习向导
vscode可以安装Cucumber (Gherkin) Full Support插件设置Gherkin语法高亮提示等

npm i @bahmutov/cypress-esbuild-preprocessor -D
npm i @badeball/cypress-cucumber-preprocessor -D
Enter fullscreen mode Exit fullscreen mode
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').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
    },
    specPattern: 'cypress/e2e/**/*.feature', // 设置 .feature 文件的路径
  },
})

Enter fullscreen mode Exit fullscreen mode

在 support/commands.js 中定义一些通用步骤:

Cypress.Commands.add('login', (username, password) => {
  cy.visit('/login')
  cy.get('#username').type(username)
  cy.get('#password').type(password)
  cy.get('button[type="submit"]').click()
})

// 然后在步骤定义文件中使用这些公共命令:

import { Given, When, Then } from 'cypress-cucumber-preprocessor/steps'

Given('I open the login page', () => {
  cy.login('user', 'password')
})

Then('I should see the dashboard', () => {
  cy.url().should('include', '/dashboard')
})

Enter fullscreen mode Exit fullscreen mode

login.feature文件

 Feature: User Login

  Scenario: User logs in with valid credentials
    Given I open the login page
    When I enter valid credentials
    Then I should be redirected to the dashboard

Enter fullscreen mode Exit fullscreen mode

对应的步骤定义文件可以命名为 loginSteps.js,并放在同一个目录下:

import { Given, When, Then } from 'cypress-cucumber-preprocessor/steps'

Given('I open the login page', () => {
  cy.visit('/login')
})

When('I enter valid credentials', () => {
  cy.get('#username').type('user')
  cy.get('#password').type('password')
  cy.get('button[type="submit"]').click()
})

Then('I should be redirected to the dashboard', () => {
  cy.url().should('include', '/dashboard')
})

Enter fullscreen mode Exit fullscreen mode

Top comments (0)