Cypress + Cucumber 绕过UI登录及session场景级清理配置问题
解决方案
你遇到的session跨步骤被清理的问题,需要从Cypress核心配置、Cucumber预处理器配置、自定义login命令优化三个维度调整:
1. 调整Cypress全局配置
打开你的cypress.config.js(或对应ts/cjs文件),修改以下配置:
const { defineConfig } = require('cypress') const createBundler = require('@bahmutov/cypress-esbuild-preprocessor') const preprocessor = require('@badeball/cypress-cucumber-preprocessor') const createEsbuildPlugin = require('@badeball/cypress-cucumber-preprocessor/esbuild') module.exports = defineConfig({ e2e: { // 重点:关闭测试间的隔离清理,Cypress 12+默认是true,会在每个it块之间清空所有上下文 testIsolation: false, // 可选:如果需要同一个账号的session跨多个spec文件复用,开启这个配置 experimentalSessionAndOrigin: true, async setupNodeEvents(on, config) { await preprocessor.addCucumberPreprocessorPlugin(on, config) on( 'file:preprocessor', createBundler({ plugins: [createEsbuildPlugin.default(config)], }) ) return config }, specPattern: "**/*.feature" } })
如果你用的是Cypress 13+,也可以把testIsolation设为"between-specs",只会在不同spec文件执行完后清理上下文,不会在同个spec的不同测试/步骤之间清理。
2. 调整Cucumber预处理器配置
在项目根目录的package.json里添加以下配置,确保每个Scenario对应一个独立测试块,不会把单个Step拆成独立测试:
{ "cypress-cucumber-preprocessor": { "stepDefinitions": "cypress/e2e/step_definitions/**/*.js", "filterSpecs": true, "omitFiltered": true, // 重点:不要将每个步骤作为独立测试用例执行 "isolatedSteps": false } }
如果你的preprocessor版本是v18以上,isolatedSteps默认就是false,可跳过这个配置,直接确认配置即可。
3. 优化自定义login命令
给cy.session添加validate校验逻辑,避免Cypress误判session失效重复执行登录流程:
Cypress.Commands.add('login', (username, password) => { cy.session([username, password], () => { cy.visit('/') cy.get(selectors.user_input,{ timeout: 60000 }).type(username) cy.get(selectors.login_button, { timeout: 60000 }).should('be.visible') cy.get(selectors.login_button).click() cy.wait(2000) cy.get(selectors.password_input, { timeout: 60000 }).should('be.visible') cy.get(selectors.submitButton, { timeout: 60000 }).should('be.visible') cy.get(selectors.password_input).type(password) cy.get(selectors.submitButton).click() cy.get(selectors.homePage, { timeout: 60000 }).should('be.visible') }, { // 每次调用login命令时校验session是否有效,有效就直接复用,不会重新走登录流程 validate() { cy.visit('/') // 校验登录后的首页元素存在,说明session有效 cy.get(selectors.homePage, { timeout: 10000 }).should('exist') }, // 可选:如果需要跨spec复用session,开启这个配置 cacheAcrossSpecs: true }) })
4. 调整步骤调用逻辑
你的示例场景里Given和When步骤都调用了登录逻辑,建议统一把登录逻辑放到Before钩子或者仅在Given步骤调用一次,后续步骤不需要重复调用login命令,直接操作即可。
内容的提问来源于stack exchange,提问作者BugBee
相关产品推荐
相关产品推荐

