17

I am using globalThis property specifically globalThis.scrollTo(0,0) in my React WebApp.

I am using Jest for unit testing alongwith Enzyme.

As of test cases fail as it is unable to identify globalThis and says that 'globalThis' is undefined.

Is there a way to introduce globalThis into the tests just like jsdom does for window etc ?

For Example

-- abc.tsx --

const abc: React.FC<CustomProps> = props => {
useEffect(() => {
globalThis?.scrollTo(0,0);
}
}

-- abcTest.tsx --

wrapper = mount(<abc/>);

mount produces error that "globalThis" is undefined

skyboyer
  • 22,209
  • 7
  • 57
  • 64
INDER
  • 343
  • 1
  • 4
  • 15

2 Answers2

28

globalThis needs node version 12+. I use n as node version management.

console.log(globalThis);

For node/10.16.2, got error:

console.log(globalThis);
            ^

ReferenceError: globalThis is not defined

For node/12.6.1, got:

Object [global] {
  global: [Circular],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] },
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(util.promisify.custom)]: [Function]
  }
}

See also, MDN globalThis#compatibility

Lin Du
  • 88,126
  • 95
  • 281
  • 483
1

You can add these code to the top

!function(t){function e(){var e=this||self;e.globalThis=e,delete t.prototype._T_}"object"!=typeof globalThis&&(this?e():(t.defineProperty(t.prototype,"_T_",{configurable:!0,get:e}),_T_))}(Object);

More details

Elikill58
  • 4,050
  • 24
  • 23
  • 45
timedgqb
  • 11
  • 1