运行Cypress测试后页面空白问题求助
问题描述
运行Cypress 10.4.0测试时,测试页面始终处于空白状态,点击测试步骤也无任何UI渲染。本地服务为Next.js项目,Node版本为v16.16.0,相关截图及代码如下:

测试代码:
describe("home page", () => { beforeEach(() => { cy.visit("http://localhost:3000") }) context("Hero section", () => { it("the h1 contains the correct text", () => { cy.getByData("hero-heading").contains( "Testing Next.js Applications with Cypress" ) }) it("the features on the homepage are correct", () => { cy.get("dt").eq(0).contains("4 Courses") cy.get("dt").eq(1).contains("25+ Lessons") cy.get("dt").eq(2).contains("Free and Open Source") }) }) context("Courses section", () => { it("CourseL Testing Your First Next.js Application", () => { cy.getByData('course-0') .find('a') .eq(3) .contains('Get started') }) }) }) /// <reference types="cypress" /> Cypress.Commands.add('getByData', (selector) => { return cy.get(`[data-test=${selector}]`); });
解决步骤
确认本地服务正常运行
手动在浏览器打开http://localhost:3000,确保页面能正常渲染。Cypress不会自动启动应用服务,必须提前通过npm run dev或对应命令启动Next.js项目。修复自定义命令语法问题
现有getByData命令中,data-test属性值未加引号,若selector包含特殊字符会导致选择失败,修正后代码:Cypress.Commands.add('getByData', (selector) => { return cy.get(`[data-test="${selector}"]`); // 给属性值添加双引号 });检查Cypress配置文件
Cypress 10+使用cypress.config.js作为配置文件,确保配置正确:- 设置
baseUrl为http://localhost:3000,简化访问路径 - 若开启了
experimentalSessionAndOrigin,尝试暂时禁用该实验特性,部分Next.js项目会因该选项出现渲染异常
示例配置:
const { defineConfig } = require("cypress"); module.exports = defineConfig({ e2e: { baseUrl: "http://localhost:3000", // experimentalSessionAndOrigin: true, // 注释或设为false测试 }, });- 设置
清除Cypress缓存
运行以下命令清除缓存,避免旧缓存导致的异常:npx cypress cache clear之后重新启动Cypress测试。
切换测试浏览器
尝试使用Chrome稳定版运行测试,Cypress默认的Electron浏览器可能和部分Next.js项目存在兼容性问题,在Cypress启动界面选择Chrome即可。检查Next.js终端日志
查看Next.js开发服务的终端输出,确认是否存在编译错误、资源加载失败等问题,这些项目本身的错误会直接导致页面空白,需优先解决。
内容的提问来源于stack exchange,提问作者tragsdale7
相关产品推荐
相关产品推荐

