使用Jest测试方法

时间:2019-07-04 08:57:35

标签: javascript reactjs react-redux

我是React和Jest的新手,我试图测试自己的goBack()函数,但是每次使用jest.spyOn时,它总是告诉我它不是函数。有人对此有解决方案吗? 我曾经使用spyOn方法来尝试监视该方法,但是它一直给我未定义的信息 这是我的课程组件:

class Contribute extends React.Component {
    goBack = () => {
        this.props.history.goBack();
    };

    render() {
        return (
            <div className="no-navbar">
                <div className="col-lg-6 pledge-pane pledge-pane-lg" id="imageMobile">
                    <div className="mx-2 container" id="back-button-mobile">
                        <button className="btn btn-outline-secondary btn-circle" onClick={this.goBack}>
                            <i className="fa fa-arrow-left"> </i>
                        </button>
                    </div>`

这是我关于goBack函数的测试文件:

it('test onClick function', () => {
        let props = {
            history:{
                goBack: jest.fn()
            }
        };
        const spy = jest.spyOn(Contribute.prototype, 'goBack');
        const wrapper = mount(<Contribute {...props}/>);
        Contribute.find('#back-button-mobile').simulate('click', {
            preventDefault: () => {
            }
        });
        expect(spy).toHaveBeenCalled();
        console.log(spy);
    });

运行测试文件时,结果如下:

Error: Cannot spy the goBack property because it is not a function; undefined given instead

0 个答案:

没有答案