简体   繁体   中英

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 scrollToTopEvent`, () => {

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

            scrollToTop.setState({ showScrollToTop: true });

            jest.spyOn(instance, 'scrollToTopEvent');

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

            scrollToTopButton.simulate('click');

            scrollToTop.update();

            expect(instance.scrollToTopEvent).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!

To be enable enzyme to track a function call you have to spy on that function, like this:

const scrollToTopEventSpy = jest.spyOn(ScrollToTop.prototype, 'scrollToTopEvent);

Then you can test the calls like this:

expect(scrollToTopEventSpy).toHaveBeenCalled();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM