samedi 15 août 2020

React Jest Testing button click called a function

I am very new to React and want to be able to test that a function was called when a button is clicked, however I cannot get this working. I have tried the answers at posts such as: How to test a function is called in react jest? and others but to no avail.

My component snippet is:

// Import React core components
import React from 'react';

class ScrollToTop extends React.Component {

    /**
    * Method to scroll top the top of the page on click
    */
    scrollToTopEvent() {
        window.scrollTo(0, 0);
    };

    render() {
        return(

            <div id="scroll-to-top-container">
                {
                    this.state.showScrollToTop ? (
                        <button id="scroll-to-top" className="button button-secondary" onClick={ this.scrollToTopEvent }>Scroll to top</button>
                    ) : (
                        null
                    )
                }
            </div>

        );
     }

     export default ScrollToTop;

}

And here is my test that I am attempting to get working, cobbled together from various Stackoverflows and articles:

import React from 'react';
import { shallow } from 'enzyme';
import ScrollToTop from "./scroll-to-top";

describe(`Tests the scroll-to-top.js file content`, () => {

    const scrollToTop = shallow(<ScrollToTop />);
    const instance = scrollToTop.instance();

    describe(`Tests scrollToTop`, () => {

        it(`should ensure the scrollToTop method was called on button click`, () => {

            scrollToTop.setState({ showScrollToTop: true });

            jest.spyOn(instance, 'scrollToTop');

            const scrollToTopButton = scrollToTop.find(`#scroll-to-top`);

            scrollToTopButton.simulate('click');

            scrollToTop.update();

            expect(instance.scrollToTop).toHaveBeenCalled();
    
        });

    });

});

The error I get in the console is:

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

> 96 |             expect(instance.scrollToTopEvent).toHaveBeenCalled();

Any help for this n00b would be much appreciated!

Aucun commentaire:

Enregistrer un commentaire