Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: scrollIntoView is not a function

I am new to react-testing-library / jest and attempting to write a test to see if the navigation of routes (using react-router-dom) is performed correctly. So far I have been following the README and this tutorial on how to use.

One of my components uses scrollIntoView in a local function and this causes the test to fail.

TypeError: this.messagesEnd.scrollIntoView is not a function    45 |   46 |     scrollToBottom = () => { > 47 |         this.messagesEnd.scrollIntoView({ behavior: "smooth" });      |                          ^   48 |     }   49 |   50 |  

This is the function in my chatbot component:

componentDidUpdate() {     this.scrollToBottom(); }  scrollToBottom = () => {     this.messagesEnd.scrollIntoView({ behavior: "smooth" }); } 

And this is a sample of the tests that fail:

test('<App> default screen', () => {      const { getByTestId, getByText } = renderWithRouter(<App />)      expect(getByTestId('index'))      const leftClick = {button: 0}     fireEvent.click(getByText('View Chatbot'), leftClick) <-- test fails      expect(getByTestId('chatbot'))  }) 

I have tried to use a mock function, however the error still remains.

This is where this.messageEnd is assigned:

    <div className="chatbot">         <div className="chatbot-messages">             //render messages here         </div>         <div className="chatbot-actions" ref={(el) => { this.messagesEnd = el; }}>             //inputs for message actions here         </div>     </div> 

I referenced code from this stack overflow question: How to scroll to bottom in react?

SOLUTION

test('<App> default screen', () => {      window.HTMLElement.prototype.scrollIntoView = function() {};      const { getByTestId, getByText } = renderWithRouter(<App />)      expect(getByTestId('index'))      const leftClick = {button: 0}     fireEvent.click(getByText('View Chatbot'), leftClick)      expect(getByTestId('chatbot'))  }) 
like image 710
Charklewis Avatar asked Nov 12 '18 22:11

Charklewis


2 Answers

scrollIntoView is not implemented in jsdom. Here's the issue: link.

You might get it working by manually adding it:

window.HTMLElement.prototype.scrollIntoView = function() {}; 
like image 193
Giorgio Polvara - Gpx Avatar answered Oct 01 '22 12:10

Giorgio Polvara - Gpx


If we want to unit test 'scrollIntoView' function in a react application using react testing library then we can mock the function using 'jest'.

window.HTMLElement.prototype.scrollIntoView = jest.fn() 
like image 36
Kriti Avatar answered Oct 01 '22 12:10

Kriti