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

1.9k views Asked by At

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)
2

There are 2 answers

0
Илья Хоришко On BEST ANSWER

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

0
Samrez Ikram On

I got this error after upgrading to node v19. Changing these lines

in

react-native/jest/setup.js

 global.performance = { 
   now: jest.fn(Date.now), 
 }; 

to something like

if (!global.performance) {
  global.performance = {}
}

global.performance.now = jest.fn(Date.now)

Might solve the issue. I'm guessing that node v18/19 started defining performance or added a guard that prevents reassigning it.