javascriptnode.jstypescriptjestjsusefaketimers

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


Error:

This error was only popping up for me when running CI for jest. I could not catch it locally in any way. Error text:

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)

Solution

  • Solution

    In src/utils/message.test.ts (your test file) use it before useFakeTimers

    Object.defineProperty(global, 'performance', {
      writable: true,
    });
    

    Result code

    Object.defineProperty(global, 'performance', {
      writable: true,
    });
    
    jest
      .useFakeTimers({ legacyFakeTimers: false })
      .setSystemTime(new Date(fakeTime));
    

    Thanks

    https://github.com/facebook/react-native/issues/35701#issuecomment-1847579429