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

如何在Cypress中使用Before Hook有序执行多个测试用例?

在Cypress中让多it测试按顺序连贯执行的方案

问题原因

Cypress默认开启**测试隔离(testIsolation)**机制,每个it块执行前会重置浏览器状态(清除缓存、Cookie、重置页面)。你当前的before钩子仅在所有it之前运行一次,第一个it执行完成后,第二个it启动时页面会回到初始状态,导致第二个it中的URL断言失败。


解决方案

方案1:关闭测试隔离(共享上下文状态)

在cypress.config.js中添加testIsolation: false配置,让所有it块共享同一个浏览器上下文,状态会在it之间保留,实现连贯执行:

module.exports = defineConfig({
  e2e: {
    testIsolation: false,
    // 其他已有配置...
  },
})

注意:此方式会打破测试隔离性,若某个it执行失败,后续it的执行状态会受影响,适合依赖前置步骤的连贯业务流程测试。

方案2:用beforeEach保持隔离(每个it前重新初始化)

如果希望测试保持独立性,可将登录及前置依赖步骤移到beforeEach钩子中,确保每个it执行前都处于正确的初始状态:

修改support/steps.js:

import * as Credentials from "../fixtures/login"

beforeEach(function () {
    cy.visit("")
    cy.contains("a", "Login").click()
    cy.get("#id_username").type(Credentials.username)
    cy.get("#id_password").type(Credentials.password)
    cy.get("[type='submit']").click()
    // 提前完成第二个it需要的前置导航
    cy.contains("a", "Creations").click()
    cy.url().should('include','/blog/')
})

修改测试文件addCreation.cy.js:

import "../support/steps"

describe('Add Personal Creation to website', () => {
    it('should verify navigation to Creations page', () => {
        cy.url().should('include','/blog/')
    })

    it('should open new creation page', () => {
        cy.get("[type='submit']").click()
        cy.url().should('include', '/blog/blog/new/')
        cy.get('legend').should('have.text', 'Name your creation here:')
    })
})

这种方式每个it都是独立的,不会互相影响,但会重复执行登录步骤,测试耗时会略有增加。


内容的提问来源于stack exchange,提问作者bogdan-cmd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 07:14:55