如何在Cypress中为两个不同文件夹分别运行独立的beforeEach()
解决方案1:拆分专属Support文件,动态加载
这个方案适合把API和UI的前置逻辑完全分开维护,结构更清晰:
- 拆分前置逻辑到独立文件
在cypress/support目录下新建两个文件:
api-support.js:存放API测试专属的beforeEach逻辑
beforeEach(() => { // 这里写API测试的前置操作,比如设置请求头、初始化测试数据等 cy.log('执行API测试专属前置操作'); cy.intercept('**/api/*', (req) => { req.headers['Authorization'] = 'Bearer your-test-token'; }); });
ui-support.js:存放UI测试专属的beforeEach逻辑
beforeEach(() => { // 这里写UI测试的前置操作,比如登录、调整窗口尺寸等 cy.log('执行UI测试专属前置操作'); cy.visit('/login'); cy.get('#username').type('test-user'); cy.get('#password').type('test-pass'); cy.get('button[type="submit"]').click(); });
- 修改Cypress配置,动态指定Support文件
打开cypress.config.js(旧版本是cypress.json),通过setupNodeEvents根据测试文件路径判断加载哪个Support文件:
const { defineConfig } = require("cypress"); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { // 根据当前运行的测试文件路径匹配 const targetSpec = config.specPattern; if (targetSpec.includes('/API/')) { config.supportFile = 'cypress/support/api-support.js'; } else if (targetSpec.includes('/UI/')) { config.supportFile = 'cypress/support/ui-support.js'; } return config; }, specPattern: 'cypress/integration/**/*.spec.js', }, });
- 运行测试时指定对应文件夹
- 跑API测试:
npx cypress run --spec "cypress/integration/API/**/*.spec.js"
- 跑UI测试:
npx cypress run --spec "cypress/integration/UI/**/*.spec.js"
解决方案2:在全局Support文件中做条件判断
如果你的前置逻辑不算特别复杂,这个方案更简单,不需要拆分文件,直接在support/index.js里根据当前测试文件路径分支执行:
beforeEach(() => { // 获取当前运行的测试文件路径 const currentSpecFile = Cypress.spec.file; // 判断是API还是UI测试,执行对应逻辑 if (currentSpecFile.includes('/API/')) { // API测试专属前置操作 cy.log('API测试前置:设置请求头'); // 你的API前置代码... } else if (currentSpecFile.includes('/UI/')) { // UI测试专属前置操作 cy.log('UI测试前置:自动登录'); // 你的UI前置代码... } });
这样不管你是单独跑API还是UI的测试用例,都会自动执行对应的beforeEach逻辑,不会同时触发两套前置。
注意事项
- 路径匹配时要确保文件夹名称和代码里的一致(比如是
/API/还是/api/,大小写要对应) - 如果需要跑所有测试,两种方案都会自动匹配对应文件夹的前置逻辑,不会冲突
内容的提问来源于stack exchange,提问作者Luna
相关产品推荐
相关产品推荐

