Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing ScrollIntoView in Jest

Tags:

jestjs

With the function which uses scrollIntoView

export const scrollDown = () => {
    document.querySelector('.bottom').scrollIntoView({ 
        behavior: 'smooth' 
    });
}

I have a test here that goes like this

describe('scrollDown', () => {
    let scrollIntoViewMock = jest.fn();
    window.HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;
    scrollDown()
    expect(scrollIntoViewMock).toBeCalled();
})

But the test is failing with the TypeError: Cannot set property 'scrollIntoView' of undefined

The test was from another SO answer for scrollIntoView testing question. Any help would be appreciated.

like image 877
Ricky Avatar asked Sep 15 '25 19:09

Ricky


1 Answers

You need to add an HTMLElement with class bottom to the document:

const scrollDown = () => {
  document.querySelector('.bottom').scrollIntoView({ 
      behavior: 'smooth' 
  });
}

test('scrollDown', () => {
  document.body.innerHTML = '<div class="bottom"></div>';
  const scrollIntoViewMock = jest.fn();
  HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;
  scrollDown();
  expect(scrollIntoViewMock).toBeCalledWith({ behavior: 'smooth' });  // Success!
})
like image 151
Brian Adams Avatar answered Sep 18 '25 08:09

Brian Adams