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

Next.js项目Github Actions中Cypress测试失败:getInitialProps读取错误

排查Next.js + Cypress在GitHub Actions中出现Cannot read properties of undefined (reading 'getInitialProps')的问题

核心错误分析

报错指向Document.getInitialProps(ctx)调用时Document为undefined,本地正常但CI环境异常,大概率是CI环境下Next.js的构建/启动流程与本地存在差异,结合你使用的standalone输出模式,重点从以下几个方向排查:

1. 修正standalone模式下的启动命令

你启用了output: 'standalone',Next.js会生成精简的独立运行包,但默认的next start在CI环境中可能无法正确加载完整的Document依赖。修改package.json中的start命令:

"start": "node .next/standalone/server.js"

替代原有的next start,确保CI环境下直接启动standalone打包后的服务文件,避免依赖缺失。

2. 验证next-transpile-modules与standalone模式的兼容性

withTM(next-transpile-modules)与Next.js的standalone模式存在兼容性问题,旧版本的withTM可能无法正确处理transpile后的模块在standalone包中的引用。解决方式:

  • 升级next-transpile-modules到支持Next.js 12+的最新版本
  • 若升级后仍有问题,改用Next.js原生的transpilePackages配置替代withTM(Next.js 13+推荐):
/** @type {import('next').NextConfig} */
/* eslint-disable @typescript-eslint/no-var-requires */
module.exports = {
  reactStrictMode: true,
  trailingSlash: true,
  output: 'standalone',
  swcMinify: false,
  eslint: { dirs: ['src'] },
  transpilePackages: ['react-dnd']
};

3. 简化Cypress GitHub Action配置

你的Action配置同时指定了build和command参数,可能导致构建流程重复或环境不一致:

  • cypress-io/github-action的build参数会自动执行构建并启动服务,但command参数会覆盖默认逻辑,导致构建后的服务未正确启动。
  • 改用Action内置流程处理构建和测试:
- uses: cypress-io/github-action@v4
  with:
    install-command: npm install
    build: npm run build
    start: npm run start # 使用修改后的start命令
    spec: cypress/e2e/*.ts
    browser: firefox
    headed: true

移除command参数,让Action自动完成build→start→等待服务就绪→运行测试的流程,避免手动命令的环境冲突。

4. 检查Document的导入正确性

确保_document.tsx中完整导入Next.js的Document类:

import Document, { Html, Head, Main, NextScript } from 'next/document';

若导入路径错误或不完整,本地开发环境可能通过热加载兼容,但CI打包后会出现依赖缺失导致Document为undefined。

5. 保证CI环境依赖安装的一致性

在GitHub Actions中使用npm ci替代npm install,确保依赖版本与package-lock.json完全一致,避免本地与CI的依赖差异:

install-command: npm ci

额外调试建议

  • 在CI构建步骤后添加目录检查命令,确认standalone包结构完整:
- run: ls -la .next/standalone
  • 在Cypress测试中添加异常监听,捕获更详细的错误栈:
Cypress.on('uncaught:exception', (err, runnable) => {
  console.error('Uncaught exception stack:', err.stack);
  return false; // 阻止Cypress自动失败测试,以便查看完整错误信息
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:05:26