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

Jest CI运行时报错:无法赋值给global的只读属性performance

解决Jest CI环境下performance只读属性赋值错误

问题现象

CI环境运行Jest测试时触发以下错误,本地环境无此问题:

FAIL src/utils/message.test.ts
● Test suite failed to run

TypeError: Cannot assign to read only property 'performance' of object '[object global]'

   5 |
   6 | jest
>  7 |   .useFakeTimers({ legacyFakeTimers: false })
     |    ^
   8 |   .setSystemTime(new Date(fakeTime));
   9 |
  10 | jest.mock('src/constants/env', () => {

  at hijackMethod (../node_modules/@sinonjs/fake-timers/src/fake-timers-src.js:946:32)
  at Object.install (../node_modules/@sinonjs/fake-timers/src/fake-timers-src.js:1733:17)
  at Object.<anonymous> (src/utils/message.test.ts:7:4)

可行解决方案

  • 切换到legacyFakeTimers模式
    修改测试代码中的useFakeTimers配置:

    jest
      .useFakeTimers({ legacyFakeTimers: true })
      .setSystemTime(new Date(fakeTime));
    

    新的fake timers默认实现在部分CI环境的全局对象上无权限修改performance属性,回退到旧模式可规避该问题。

  • 排除performance API的模拟
    若测试不需要用到performance相关模拟,显式排除它:

    jest
      .useFakeTimers({
        legacyFakeTimers: false,
        doNotFake: ['performance']
      })
      .setSystemTime(new Date(fakeTime));
    

    避免fake timers尝试修改只读的performance属性。

  • 对齐CI与本地的Node.js版本
    部分旧版Node.js的全局performance属性为只读,而本地可能使用了更新版本。检查CI环境Node.js版本,升级至与本地一致的版本。

  • 锁定@sinonjs/fake-timers版本
    错误来自该依赖的兼容性问题,在package.json中锁定版本确保CI与本地一致:

    "resolutions": {
      "@sinonjs/fake-timers": "9.1.2" // 替换为本地正常工作的版本
    }
    

    npm需配合npm-force-resolutions生效,yarn直接支持该配置。

内容的提问来源于stack exchange,提问作者Илья Хоришко

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:28:15