模拟('submit')后,Jest / Enzyme测试失败“this.props.searchUser不是函数”

时间:2017-07-20 20:57:46

标签: javascript reactjs react-redux enzyme jest

  

FAIL客户端/容器/ Users / userListContainer.test.js     ●tests>用户搜索后应显示用户

预期

模拟点击后,测试找到容器中的2个li应该通过

结果

获取> this.props.searchUser不是函数

userListContainer.js

import React, { Component } from "react"
import { connect } from 'react-redux'

import { UserList } from '../../components'

// Actions
import { searchUser } from '../../actions'

export class UserListContainer extends Component {
    constructor(props) {
        super(props);
    }

    onFormSubmit(e, user) {
        e.preventDefault();
        this.props.searchUser(user)
    }

    render() {
        return (
            <div className='users-container'>
                <UserList
                    users={this.props.users}
                    lastUserSearched={this.props.lastUserSearched}
                    onFormSubmit={this.onFormSubmit.bind(this)}
                />
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        users: state.usersReducer.users,
        lastUserSearched: state.usersReducer.lastUserSearched
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        searchUser: (user) => {dispatch(searchUser(user))},
    }
}

const userList = UserListContainer;
export default connect(mapStateToProps, mapDispatchToProps)(userList)

UserList操作

import * as actionTypes from '../../actionTypes'

export const searchUser = (user) => ({
  type: actionTypes.SEARCH_USER,
  payload: user
});

测试代码

import React from 'react'
import * as enzyme from 'enzyme'
import { shallow, mount } from 'enzyme'
import toJson from 'enzyme-to-json'
import { UserListContainer } from './UserListContainer'
import userList from './UserListContainer'

const userListContainer = shallow(<UserListContainer />);

describe('<UserListContainer /> tests', () => {
    let wrapper;

    beforeAll(() => {
        wrapper = mount(<UserListContainer />);
    });

    it('Should render', () => {
        const tree = toJson(userList);
        expect(tree).toMatchSnapshot();
    });

    it('Should show User after a user searches', () => {
        wrapper.find('form label input').get(0).value = "ni";
        // console.log('wrapper', wrapper)
        wrapper.find('form label button.btn-blue').simulate('submit');
        expect(wrapper.find('ul li')).toHaveLength(2);
    });
});

enter image description here

1 个答案:

答案 0 :(得分:3)

您需要在测试中将道具传递给UserListContainer,包括searchUser功能。 connect在您的测试中不会为您提供。阿布拉莫夫本人实际上建议你不要测试connect

 beforeAll(() => {
    wrapper = mount(<UserListContainer searchUser={() => {}} />);
 });

如果我建议,你可能最好更多地进行这项测试&#39; unit&#39;喜欢。例如,您可以shallow挂载UserList并模拟单击,并仅监视函数以确保调用它。然后,您可以使用不同的道具再次浅层安装,以模拟发生的任何变化。同样,在您的容器中,您只需致电onFormSubmit并确保调用searchUser