如何使用 Jest 测试没有参数的 React 组件方法?

How to test React component method without parameter using Jest?

目前,我正在尝试测试我的应用程序,我正在尝试测试我的组件方法。所以这是我的组件代码:

import React, {Component} from 'react';
import PropTypes from 'prop-types';

//Style
const style = {
    box: {
        width: '96%',
        height:120,
        marginLeft: 'auto',
        marginRight: 'auto',
        marginTop: 10,
        marginBottom: 10,
        display:'flex',
    },
    votes: {
        width: '12%',
        height: '100%',
        backgroundColor: '#EEE',
        display:'block',
        textAlign: 'center',
        borderTopLeftRadius:5,
        borderBottomLeftRadius:5
    },
    detail: {
        width: '88%',
        height: '100%',
        backgroundColor: '#DDD',
        borderTopRightRadius:5,
        borderBottomRightRadius:5,
    },
    image: {
        height: '35%',
        width: '35%',
    },
}

//Component of one topic, contains all the button to upvote and downvote. 
export class OneTopic extends Component {
    constructor(props) {
        super(props);
        //bind all the function
        this.upvotes = this.upvotes.bind(this);
        this.downvotes = this.downvotes.bind(this);
    }

    //function to upvote, will call the function that passed by Topic table(but from App.jsx)
    upvotes() {
        this.props.upvote(this.props.title);
    }

    //funtion to downvote, will call the function that passed by Topic table(but from App.jsx)
    downvotes() {
        this.props.downvote(this.props.title);
    }

    render() {
        return(
            <div style={style.box}>
                <div style = {style.votes}>
                    <img src="img/upvote.png" className="vote" style={style.image} alt="upvote" onClick = {this.upvotes}/>
                        <div style={{backgroundColor:'#AAA',padding:3, width: 20, height:20, textAlign:'center', margin:'auto', fontSize:20, marginBottom:4}} >
                            {this.props.vote}
                        </div>
                    <img src="img/downvote.png" className="vote" style={style.image} alt="downvote" onClick={this.downvotes}/>
                </div>
                <div style = {style.detail}>
                    <h2 className="margin">{this.props.title} </h2><hr className="margin" />
                    <p className="margin descrip">{this.props.desc} </p>
                </div>
            </div>
            );
    }
}

请关注点赞功能。我尝试使用 Jest 实例对此进行测试,这是我的测试代码:

it('Child oneTopic is not crashing', () => {
        const wrapper = mount(<oneTopic />);
        wrapper.instance().upvotes();
    });

这是错误信息:

TypeError: wrapper.instance(...).upvotes is not a function

请帮助我,我不想使用快照,因为它看起来很复杂。

您可以使用模拟方法。

wrapper.find(".vote").first().simulate('click');

如果您想模拟其他功能,即 downVote

wrapper.childAt(0).childAt(0).childAt(0).simulate('click');  // upVote
wrapper.childAt(0).childAt(0).childAt(2).simulate('click');  // downVote

或者另一种方法是为两张图片提供唯一 ID,您可以通过 ("#upVote") 或 ("#downVote") 而不是 (".vote") 访问它