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.
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!
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With