gpt4 book ai didi

javascript - 模拟 ('submit' 后 Jest/ enzyme 测试失败 ) "this.props.searchUser is not a function"

转载 作者:行者123 更新时间:2023-11-30 09:32:59 26 4
gpt4 key购买 nike

FAIL client/containers/Users/userListContainer.test.js ● tests › Should show User after a user searches

预计

模拟点击后,测试在容器中找到2里应该可以通过

结果

得到 > 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)

用户列表操作

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

最佳答案

您需要在测试中将 props 传递给 UserListContainer,包括您的 searchUser 函数。 connect 不会在您的测试中为您获取它。阿布拉莫夫本人实际上建议您不要测试 connect

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

如果我可以建议,您最好让这个测试更像“单元”。例如,您可以shallow 挂载UserList 并模拟点击,并且仅仅监视该函数以确保它被调用。然后,您可以使用不同的 Prop 再次浅安装它,以模拟发生的任何变化。同样,在您的容器中,您可以只调用 onFormSubmit 并确保调用 searchUser

关于javascript - 模拟 ('submit' 后 Jest/ enzyme 测试失败 ) "this.props.searchUser is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45225039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com