Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'globalThis' underfined for Jest test cases

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

like image 778
INDER Avatar asked Apr 01 '20 17:04

INDER


People also ask

What is globalThis?

The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self , it's guaranteed to work in window and non-window contexts.

How do you write jest test cases?

To create a test case in Jest we use the test() function. It takes a test name string and handler function as the first two arguments. The test() function can also be called under the alias - it() .

Do I need to import jest?

In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them.


1 Answers

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]
  }
}
like image 180
slideshowp2 Avatar answered Sep 30 '22 18:09

slideshowp2