【发布时间】:2017-06-09 10:26:45
【问题描述】:
onSubmit 处理程序中的值始终是一个空对象。如何将一些值传递给它以便我可以测试追加?
测试:
const store = createStore(combineReducers({ form: formReducer }));
const setup = (newProps) => {
const props = {
...newProps,
};
expect.spyOn(store, 'dispatch');
const wrapper = mount(
<Provider store={store}>
<RegisterFormContainer {...props} />
</Provider>,
);
return {
wrapper,
props,
};
};
describe('RegisterFormContainer.integration', () => {
let wrapper;
it('should append form data', () => {
({ wrapper } = setup());
const values = {
userName: 'TestUser',
password: 'TestPassword',
};
expect.spyOn(FormData.prototype, 'append');
// Passing values as second argument DOESN'T work, it's just an empty object
wrapper.find('form').simulate('submit', values);
Object.keys(values).forEach((key) => {
expect(FormData.prototype.append).toHaveBeenCalledWith(key, values[key]));
});
expect(store.dispatch).toHaveBeenCalledWith(submit());
});
});
容器:
const mapDispatchToProps = dispatch => ({
// values empty object
onSubmit: (values) => {
const formData = new FormData();
Object.keys(values).forEach((key) => {
formData.append(key, values[key]);
});
return dispatch(submit(formData));
},
});
export default compose(
connect(null, mapDispatchToProps),
reduxForm({
form: 'register',
fields: ['__RequestVerificationToken'],
validate: userValidation,
}),
)(RegisterForm);
组件:
const Form = ({ error, handleSubmit }) => (
<form onSubmit={handleSubmit} action="">
<Field className={styles.input} name="username" component={FormInput} placeholder="Username" />
<button type="submit">
Register
</button>
</form>
);
【问题讨论】:
-
你能展示你用来测试
submit是否被正确的表单值调用的实际expect子句吗? -
@jakee 完成。我在我的 jsdom 中使用
formdata-polyfill作为 FormData 否则它将是未定义的。
标签: javascript unit-testing reactjs redux-form