Skip to content

Commit

Permalink
RN: Object.defineProperties for Jest Globals (#37046)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: #37046

Changes React Native's `jest/setup.js` so that globals (e.g. `__DEV__`, `performance`, `window`) are defined using `Object.defineProperties` instead of using object property assignment.

This makes the setup logic more resilient to Jest environments (e.g. [`jsdom`](https://github.com/jsdom/jsdom/blob/master/lib/jsdom/browser/Window.js#L422-L424)) where the globals are defined without a setter (i.e. `set` is undefined) or without `writable: true`, because object property assignment to such properties throws an error in strict mode.

Changelog:
[General][Changed] - Jest globals are now defined using `Object.defineProperties` instead of object property assignment

Reviewed By: motiz88

Differential Revision: D45202142

fbshipit-source-id: 5511e374ac6ba051ad0c224b902fb6f20960e9be
  • Loading branch information
yungsters authored and facebook-github-bot committed Apr 24, 2023
1 parent 3ca188b commit cf631ad
Showing 1 changed file with 40 additions and 15 deletions.
55 changes: 40 additions & 15 deletions packages/react-native/jest/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,46 @@ const mockComponent = jest.requireActual('./mockComponent');
jest.requireActual('@react-native/js-polyfills/Object.es8');
jest.requireActual('@react-native/js-polyfills/error-guard');

global.__DEV__ = true;

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

global.regeneratorRuntime = jest.requireActual('regenerator-runtime/runtime');
global.window = global;

global.requestAnimationFrame = function (callback) {
return setTimeout(() => callback(jest.now()), 0);
};
global.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
Object.defineProperties(global, {
__DEV__: {
configurable: true,
enumerable: true,
value: true,
writable: true,
},
cancelAnimationFrame: {
configurable: true,
enumerable: true,
value: id => clearTimeout(id),
writable: true,
},
performance: {
configurable: true,
enumerable: true,
value: {
now: jest.fn(Date.now),
},
writable: true,
},
regeneratorRuntime: {
configurable: true,
enumerable: true,
value: jest.requireActual('regenerator-runtime/runtime'),
writable: true,
},
requestAnimationFrame: {
configurable: true,
enumerable: true,
value: callback => setTimeout(() => callback(jest.now()), 0),
writable: true,
},
window: {
configurable: true,
enumerable: true,
value: global,
writable: true,
},
});

// there's a __mock__ for it.
jest.setMock(
Expand Down

0 comments on commit cf631ad

Please sign in to comment.