React Jest Testing按钮单击称为函数

时间:2020-08-15 15:38:18

标签: javascript reactjs testing jestjs enzyme

我对React还是很陌生,希望能够测试单击按钮时是否调用了某个函数,但是我无法正常工作。我在How to test a function is called in react jest?等帖子中尝试了答案,但无济于事。

我的代码段是:

<title><%= htmlWebpackPlugin.options.title %></title>

这是我正在尝试工作的测试,从各种Stackoverflows和文章中整理而成:

// 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;

}

我在控制台中收到的错误是:

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();
    
        });

    });

});

对此n00b的任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

要使酶能够跟踪功能调用,您必须监视该功能,如下所示:

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

然后您可以像这样测试呼叫:

expect(scrollToTopEventSpy).toHaveBeenCalled();