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

Cypress中Before钩子在测试中多次执行的问题求助

Cypress Before钩子重复执行问题解决

问题原因

你代码里的before钩子定义在describe块外部,属于根级钩子。每次调用runTests函数,都会注册一个新的根级before。Cypress会收集所有根级钩子,在所有测试用例执行前按注册顺序全部执行,所以会先跑10次cy.visit,再执行所有测试。

解决方案

场景1:所有测试共享一次页面访问

如果希望10个测试用例只执行一次cy.visit,把before移到循环和函数外部,只定义一次,再在循环中生成测试用例:

before(() => {
  cy.visit('https://google.com')
})

describe('Tests some stuff', () => {
  function runTests(index) {
    it(`Tests with index ${index}`, () => {
      cy.log(index)
    })
  }
  
  for (let i = 0; i < 10; i++) {
    runTests(i)
  }
})

场景2:每个测试组单独执行页面访问

如果每个index对应的测试组(可包含多个it)需要单独访问页面,把before放到describe内部,这样每个组的before只会在该组测试前运行一次:

function runTests(index) {
  describe(`Test group for index ${index}`, () => {
    before(() => {
      cy.visit('https://google.com')
    })

    it('Tests some stuff', () => {
      cy.log(index)
    })
    // 可添加更多同组测试用例
  })
}
  
for (let i = 0; i < 10; i++) {
  runTests(i)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:17:41