How to spy on window.scrollTo in Jest?

Amir Hoseinian picture Amir Hoseinian · Mar 31, 2017 · Viewed 17.9k times · Source

I got a very simple react component with following functionallity:

componentDidMount() {
  window.scrollTo(0, 0)
}

It seems that you cannot do something like

window.scrollTo = jest.fn()

to spy on scrollTo function.

Therefor, I want to know what is the best way to spy on this function and assert that it has been used in my tests.

Thanks

Answer

Andreas Köberle picture Andreas Köberle · Apr 1, 2017

In jest the global name space must be accessed by global not window.

global.scrollTo = jest.fn()