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

Cypress第二个测试用例无法继承浏览器上下文,请求排查

Cypress测试用例无法继承浏览器上下文的解决方法

在Cypress中,第二个测试用例(it块)默认会启动全新浏览器实例,无法继承第一个测试的上下文状态,导致直接操作页面元素失败。

测试代码

/// <reference types="cypress" />

describe("learn about Locators", ()=> {

it("visit the google page" , ()=> {
    cy.visit("https://www.google.com/");
    cy.get("input");
    cy.get('#APjFqb').type("test");
});

 it("can locate a button on the page ",()=> {

    cy.get('#APjFqb').type("test");
    //cy.visit("https://www.google.com/");
    //cy.get('#APjFqb').type("test").
    //cy.get('textarea[title="Search]');

 });
});

配置文件(cypress.config.js)

const { defineConfig } = require("cypress");

module.exports = defineConfig({
e2e: {
  setupNodeEvents(on, config) {
  // implement node event listeners here
  },
 //excludeSpecPattern: "**/2-advanced-examples/*"
   },
  });

原因分析

Cypress的核心设计原则是测试用例隔离,每个it块都会自动重置浏览器上下文:清除所有cookie、localStorage,关闭标签页,启动全新的会话。这样可以避免测试用例之间的依赖,保证每个测试都能独立运行。

解决方法

方法1:合并测试步骤到同一个it块(推荐)

如果两个步骤属于同一个测试场景,直接合并到一个it中,确保流程连续:

/// <reference types="cypress" />

describe("learn about Locators", ()=> {

it("visit google and operate search box" , ()=> {
    cy.visit("https://www.google.com/");
    cy.get("input");
    cy.get('#APjFqb').type("test");
    // 执行原第二个测试的操作
    cy.get('#APjFqb').type("test");
});
});

方法2:使用钩子函数共享前置操作

如果需要多个it块共享相同的前置步骤(比如访问页面),使用beforeEach钩子在每个测试执行前初始化环境:

/// <reference types="cypress" />

describe("learn about Locators", ()=> {

// 每个it执行前先访问谷歌页面
beforeEach(() => {
  cy.visit("https://www.google.com/");
});

it("visit the google page" , ()=> {
    cy.get("input");
    cy.get('#APjFqb').type("test");
});

it("can locate a button on the page ",()=> {
    cy.get('#APjFqb').type("test");
 });
});

方法3:禁用测试隔离(不推荐)

如果必须保留测试间的上下文状态,可以通过配置关闭测试隔离功能,但这种方式可能导致测试依赖,降低稳定性:

全局配置(修改cypress.config.js)

const { defineConfig } = require("cypress");

module.exports = defineConfig({
e2e: {
  setupNodeEvents(on, config) {
  },
  testIsolation: false // 全局禁用测试隔离
   },
  });

局部禁用(单个describe或it)

/// <reference types="cypress" />

// 仅当前describe下的测试禁用隔离
describe("learn about Locators", { testIsolation: false }, ()=> {

it("visit the google page" , ()=> {
    cy.visit("https://www.google.com/");
    cy.get("input");
    cy.get('#APjFqb').type("test");
});

it("can locate a button on the page ",()=> {
    cy.get('#APjFqb').type("test");
 });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 01:37:38