在jest中测试redux表单,可以按照以下步骤进行:
下面是一个示例代码:
import React from 'react';
import { connect } from 'react-redux';
import { submitForm } from '../actions/formActions';
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
}
handleUsernameChange = (e) => {
this.setState({ username: e.target.value });
}
handlePasswordChange = (e) => {
this.setState({ password: e.target.value });
}
handleSubmit = (e) => {
e.preventDefault();
this.props.submitForm(this.state);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.username} onChange={this.handleUsernameChange} />
<input type="password" value={this.state.password} onChange={this.handlePasswordChange} />
<button type="submit">Submit</button>
</form>
);
}
}
const mapDispatchToProps = {
submitForm
};
export default connect(null, mapDispatchToProps)(MyForm);
测试用例示例:
import React from 'react';
import { mount } from 'enzyme';
import configureStore from 'redux-mock-store';
import { Provider } from 'react-redux';
import MyForm from '../MyForm';
const mockStore = configureStore([]);
describe('MyForm', () => {
let store;
let wrapper;
beforeEach(() => {
store = mockStore({});
wrapper = mount(
<Provider store={store}>
<MyForm />
</Provider>
);
});
it('should update the username field when input value changes', () => {
const usernameInput = wrapper.find('input[type="text"]');
usernameInput.simulate('change', { target: { value: 'test' } });
expect(wrapper.find('input[type="text"]').prop('value')).toEqual('test');
});
it('should update the password field when input value changes', () => {
const passwordInput = wrapper.find('input[type="password"]');
passwordInput.simulate('change', { target: { value: 'password' } });
expect(wrapper.find('input[type="password"]').prop('value')).toEqual('password');
});
it('should dispatch an action when form is submitted', () => {
const form = wrapper.find('form');
form.simulate('submit');
const actions = store.getActions();
expect(actions).toEqual([{ type: 'SUBMIT_FORM', payload: { username: '', password: '' } }]);
});
});
在上面的示例代码中,通过使用mount函数渲染MyForm组件,并传递mock的store,然后使用enzyme提供的模拟事件函数simulate模拟输入和提交操作。最后,通过使用expect函数对表单状态和Redux action进行验证。
对于上述示例中的action和reducer的定义,可以根据具体项目的需求进行调整。在实际项目中,可以使用redux-thunk来处理异步的表单提交操作,使用redux-mock-store来创建一个模拟的Redux store,以便在测试中进行状态的验证。
同时,如果需要对表单的验证逻辑进行测试,可以使用enzyme提供的相关方法,如wrapper.instance().validate()
来直接调用组件中的验证函数进行测试。
以上是一个基本的示例,具体的实现可能会根据项目的需求和使用的相关库有所差异。对于更复杂的表单,还可以使用其他工具、库或模块来辅助测试,例如react-testing-library、redux-saga等。
希望以上回答能够满足您对jest中测试redux表单的需求。如果还有其他问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云