笑话和酵素测试片段

时间:2018-10-31 21:23:14

标签: reactjs jestjs enzyme

我有此文件,但我想对其进行测试,但其中一些行未涵盖,如何在reactjs中使用Jest和Enzyme对它们进行测试。

const List = props => (
    <div className={styles['comments-list']}>
        <h5 className={styles['comment-header']}>Comments</h5>
        <ul className="collection">
            {props.comments.map(comment =>
                <li className="collection-item avatar" key={comment.id}>
                    <img src={IMG} alt="" className="circle"/>
                    <span className="title"><b>{comment.author}</b></span><br/>
                    <span className={`title ${styles['date-font-size']}`}><i>{formatDate(comment.created_at)}</i></span>
                    <p className={styles['comment-body']}>
                        <br/>
                        {comment.body}
                    </p>
                    <div className="secondary-content">
                        <i className={`material-icons ${styles['icon-red']}`} onClick={event => props.deleteComment(comment.id)}>delete</i>
                        <i className="material-icons" onClick={(e) => {
                            $('#foo').modal('open')
                            props.editComment(comment)
                        }}>edit</i>
                        <i className="material-icons">reply</i>
                    </div>

                </li>)}
        </ul>
    </div>
);

在上面的代码段中,未测试以下几行,其余的是:

<li className="collection-item avatar" key={comment.id}>

<i className={`material-icons ${styles['icon-red']}`} onClick={event => props.deleteComment(comment.id)}>delete</i>



$('#foo').modal('open')
props.editComment(comment)

现在上面的代码行是我的项目中未测试的行,如何在Jest或Enzyme中对其进行测试。

以下是其中一项测试:

it('should test List component', () => {

        wrapper = shallow(
            <List deleteComment='Success!'  editComment={jest.fn} comments={[]} handleChange={jest.fn} body={''} />
        );

        const tree = renderer.create(<List comments={[]}  handleChange={jest.fn} body={''} />).toJSON();
        expect(tree).toMatchSnapshot();
        expect(wrapper.find('li')).toHaveLength(0)

        expect(wrapper.props().deleteComment).toEqual(undefined)
        expect(wrapper.props().editComment).toEqual(undefined)


    });

1 个答案:

答案 0 :(得分:0)

在测试中,您提供了空的注释列表comments={[]},因此props.comments.map中的代码从不执行。再添加一个测试,以检查您的组件是否呈现注释:

it('should test List component with comments', () => {

    const comments = [
        {
            id: 1,
            author: 'John',
            body: 'Hello world'
        }
    ];

    const wrapper = shallow(
        <List deleteComment='Success!'  editComment={jest.fn} comments={comments} handleChange={jest.fn} body={''} />
    );
});