gpt4 book ai didi

reactjs - Jest - 在表单的 handleSubmit 中模拟函数调用

转载 作者:行者123 更新时间:2023-11-28 21:19:31 26 4
gpt4 key购买 nike

我正在尝试编写一个测试来模拟在表单的 handleSubmit 中调用一个函数,但是,我无法证明该函数已被调用。

形式如下:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import signUp from '../../actions/users/sign_up';
import PropTypes from 'prop-types';

class Signup extends Component {
constructor (props) {
super(props);

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.showError = this.showError.bind(this);
}

handleChange(event) {
const target = event.target;

this.setState({ [ target.name ]: target.value });
}

handleSubmit(event) {
event.preventDefault();
this.props.signUp(this.state);
}

showError(type) {
if (this.state && this.state.error && this.state.error.data.errors[ type ]) {
return this.state.error.data.errors[ type ][ 0 ];
}
}

componentDidUpdate (prevProps, prevState) {
const props = this.props;

if (prevProps === props) {
return;
}

this.setState({
...props,
});
}

render () {
return (
<div className='container-fluid'>
<div className='row'>
<div className='col col-md-6 offset-md-3 col-sm-12 col-12'>
<div className='card'>
<div className='card-header'>
<h4>Sign Up</h4>
</div>
<div className='card-body'>
<form onSubmit={ this.handleSubmit } >
<div className="form-row">
<div className="form-group col-md-12">
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
className={ `form-control ${ this.showError('email') ? 'is-invalid' : '' }` }
id="email"
placeholder="Email"
onChange={ this.handleChange }
/>
<div className="invalid-feedback">
{ this.showError('email') }
</div>
</div>
</div>
<div className="form-row">
<div className="form-group col-md-12">
<label htmlFor="username">Username</label>
<input
type="text"
name="username"
className={ `form-control ${ this.showError('username') ? 'is-invalid' : '' }` }
id="username"
placeholder="Username"
onChange={ this.handleChange }
/>
<div className="invalid-feedback">
{ this.showError('username') }
</div>
</div>
</div>
<div className="form-row">
<div className="form-group col-md-12">
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
className={ `form-control ${ this.showError('password') ? 'is-invalid' : '' }` }
id="password"
placeholder="Password"
onChange={ this.handleChange }
/>
<div className="invalid-feedback">
{ this.showError('password') }
</div>
</div>
<button type="submit" className="btn btn-primary">Sign Up</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}

function mapStateToProps (state) {
return {
email: state.UsersReducer.email,
username: state.UsersReducer.username,
password: state.UsersReducer.password,
error: state.UsersReducer.error,
}
}

function mapDispatchToProps (dispatch) {
return bindActionCreators({
signUp: signUp,
}, dispatch);
}

Signup.propTypes = {
email: PropTypes.string,
username: PropTypes.string,
password: PropTypes.string,
signUp: PropTypes.func.isRequired
}

export default connect(mapStateToProps, mapDispatchToProps)(Signup);

signUp 操作如下所示:

import { SIGN_UP, SHOW_USER_ERRORS } from '../types';
import axios from 'axios';
import { API_ROOT, setLocalStorageHeader } from './../../api-config';
import { push } from 'react-router-redux';

export default function signUp (params) {
return dispatch => {
axios.post(`${ API_ROOT }/auth.json`, params).then(res => {
setLocalStorageHeader(res);
dispatch(push('/profile'));
dispatch(signUpAsync(res.data));
}).catch(error => {
dispatch({ type: SHOW_USER_ERRORS, payload: { error: error.response } });
});
}
}

function signUpAsync (data) {
return {
type: SIGN_UP,
payload: data
};
}

我试图模拟这样一个事实,即表单将使用从表单输入中获得的值提交,这些值处于表单状态( emailusernamepassword )。

我目前的测试是:

import React from 'react';
import { shallow, mount } from 'enzyme';
import configureStore from 'redux-mock-store';
import { bindActionCreators } from 'redux';
import thunk from 'redux-thunk';

import Signup from '../../../components/users/signup';
import UsersReducer from '../../../reducers/reducer_users';

describe('<Signup />', () => {
describe('render()', () => {
test('submits the form data', async () => {
const mockStore = configureStore([thunk]);

const initialState = {
UsersReducer: {
email: '',
username: '',
password: '',
},
};

const store = mockStore(initialState);
const dispatchMock = jest.spyOn(store, 'dispatch');

const signUp = jest.fn();

const wrapper = shallow(<Signup store={store} signUp={signUp} />);
const component = wrapper.dive();

component.find('#email').simulate(
'change', {
target: {
name: 'email', value: 'foo@gmail.com'
}
}
);

component.find('#email').simulate(
'change', {
target: {
name: 'username', value: 'foo'
}
}
);

component.find('#password').simulate(
'change', {
target: {
name: 'password',
value: '1234567',
}
}
)

component.find('form').simulate(
'submit', {
preventDefault() {}
}
)

expect(dispatchMock).toHaveBeenCalled();

expect(signUp).toHaveBeenCalledWith({
email: 'foo@gmail.com',
username: 'foo',
password: '12345678'
});
});
});
});

但无论我尝试什么,我都会收到以下错误。

Expected mock function to have been called with:
[{"email": "foo@gmail.com", "password": "12345678", "username": "foo"}]
But it was not called.

我认为这是因为 signUp 没有在 shallow(<Signup store={store} signUp={signUp} />) 中被正确模拟,因为当我执行 console.log(wrapper.props()) 时,我得到:

{
...
signUp: [Function],
...
}

而不是表明它是一个模拟函数:

{ [Function: mockConstructor]
_isMockFunction: true,
...
}

我知道测试通过的 signUp 正在调用 dispatch 操作。当我向其中添加 params 时,我还可以在 signUp 操作中看到 console.log(params)

如有任何帮助,我们将不胜感激。

最佳答案

将 redux 添加到 View 时,在 mapDispatchToProps 中添加 signUp

当您使用 redux-mock-store 时,您可以访问 store.getActions() 调用的所有操作,因此在您的情况下,无需传递 signUp 作为 spy ,它将被 mapDispatchToProps 覆盖,它可能看起来像这样:

const signUpCall = store.getActions()[0]

expect(signUpCall).toHaveBeenCalledWith({
email: 'foo@gmail.com',
username: 'foo',
password: '12345678'
});

关于reactjs - Jest - 在表单的 handleSubmit 中模拟函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53533460/

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