【问题标题】:React Jest Testing button click called a functionReact Jest 测试按钮点击调用一个函数
【发布时间】:2020-08-15 15:38:18
【问题描述】:

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

我的组件 sn-p 是:

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

}

这是我正在尝试开始工作的测试,由各种 Stackoverflow 和文章拼凑而成:

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

    });

});

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

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

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

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

对于这个 n00b 的任何帮助将不胜感激!

【问题讨论】:

    标签: javascript reactjs testing jestjs enzyme


    【解决方案1】:

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

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

    然后你可以像这样测试调用:

    expect(scrollToTopEventSpy).toHaveBeenCalled();
    

    【讨论】:

    • 感谢您的回复,但是这给了我相同的结果。
    • 尝试等待window.scrollTo() 怎么样,这意味着将您的expect 放在setTimeout() 中?
    • 谢谢,我确实尝试过,但它给出了误报。将期望包装在 setTimeout 中将通过测试,但反过来将其设置为 .not.toHaveBeenCalled() 也将通过测试,这应该会失败。
    • 你必须像 it('dfdfsdfsg', (done) =&gt; {...}) 这样设置测试,并在 expect 语句之后,在 setTimeout() 内放置一个 done()
    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2019-12-22
    • 2021-08-08
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多