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

Next.js+Jest项目升级Sentry v7至v8失败:TypeError读取'events'报错

解决Next.js 14.2.5(Pages路由)+ Jest + Sentry v8测试报错问题

错误详情

升级Sentry从v7到v8后,只要从@sentry/nextjs导入内容,运行Jest测试就会抛出:

TypeError: Cannot read properties of undefined (reading 'events')

解决方案

方案1:模块模拟(推荐)

通过Jest的模块映射,模拟Sentry模块避免加载真实代码,彻底解决测试环境适配问题:

  1. 修改Jest配置文件(jest.config.js/jest.config.ts),添加模块映射:
module.exports = {
  // 保留原有配置
  moduleNameMapper: {
    // 新增这一行
    '^@sentry/nextjs$': '<rootDir>/__mocks__/@sentry/nextjs.js',
  },
};
  1. 在项目根目录创建__mocks__/@sentry/nextjs.js文件,模拟项目中用到的Sentry导出方法:
// 根据你的实际使用情况补充需要的模拟方法
export const init = jest.fn();
export const captureException = jest.fn();
export const captureMessage = jest.fn();
export const withSentryConfig = (config) => config;
export const Sentry = {
  init: jest.fn(),
  captureException: jest.fn(),
  captureMessage: jest.fn(),
};

方案2:初始化全局对象

如果需要在测试环境保留Sentry功能,可在测试初始化时补全Sentry依赖的全局对象:

  1. 创建jest.setup.js文件:
// 初始化Sentry需要的全局属性
if (typeof window !== 'undefined') {
  window.__SENTRY__ = window.__SENTRY__ || {
    events: {},
  };
}
  1. 在Jest配置中引入该初始化文件:
module.exports = {
  // 保留原有配置
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};

方案3:条件加载Sentry配置

确保Next.js配置中只在非测试环境加载Sentry:

修改next.config.js:

const nextConfig = {
  // 你的Next.js基础配置
};

// 仅在非测试环境应用Sentry配置
if (process.env.NODE_ENV !== 'test') {
  const { withSentryConfig } = require('@sentry/nextjs');
  module.exports = withSentryConfig(nextConfig, {
    // 你的Sentry配置参数
  });
} else {
  module.exports = nextConfig;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 22:25:04