reactjs - Sinon 使用 Spy 进行表单验证出错
问题描述
我无法验证使用诗浓的Spy()
功能是否正确填写了表格。我的目标是通过这个单元测试:
it('check entire form validation when the form is valid', () => {
let formSpy = spy();
const form = mount(<Form isFormValid={formSpy} />);
form.find('.name').simulate('change', { target: { value: 'sasrank' } });
form.find('.email').simulate('change', { target: { value: 'aasdbc@xyz.com' } });
form.find('.phone').simulate('change', { target: { value: '9856756756' } });
form.find('.url').simulate('change', { target: { value: 'http://google.com' } });
form.find('.button').simulate('click');
expect(formSpy.calledWith(true)).toEqual(true);
});
此表单使用一些基本的 HTML5 验证
Form.js
import React, {Component} from 'react';
import {PropTypes} from 'prop-types';
class Form extends Component {
constructor(props) {
super(props);
this.state = {
isEmailValid: false,
isNameValid: false,
isPhoneValid: false,
isUrlValid: false,
};
}
render() {
return (
<div className="row">
<h1 className="text-center">Form Validation</h1>
<form>
<h3>Name:
</h3>
<input type="text" required pattern="[A-Za-z]{3,30}" className="name"></input>
<h3>Email:
</h3>
<input type="email" required className="email"></input>
<h3>Phone:
</h3>
<input type="number" required className="phone"></input>
<h3>Blog URL:
</h3>
<input type="url" required className="url"></input>
<div className="small-6 small-centered text-center columns">
<button href="#" className="button success expand round text-center">Verify</button>
</div>
</form>
</div>);
}
}
export default Form;
为了通过这个测试,我可以修改什么?
解决方案
你不使用isFormValid
任何地方Form
。React 不知道如何神奇地isFormValid
传递给React.Component
构造函数(除非你使用了一些你没有提到的神奇库。
这不是“sinon”,而是缺乏适当的实现来调用isFormValid
至少,您应该onClick
在按钮上安装回调并使用一些值调用此验证,如下所示:
<button onClick={this.handleSubmit} ...>Verify</button>
onSubmit
看起来或多或少像这样的方法:
onSubmit = (event) => {
const valuues = collectValues();
if (this.props.isFormValid(values)) {
// ... handle submit
}
}
有很多地方使用表单验证,比如这个答案也使用表单HTML5 验证 API(虽然不确定酶是否支持它)
推荐阅读
- elasticsearch - Elasticsearch嵌套查询必须和必须不具有相同的字段
- swift - 当用户停止快速输入时如何创建函数
- html - 如何根据屏幕大小重新排列 flexbox 内元素的顺序?
- python - 3D 椭球体和显示它们
- here-api - 地图图像 API - 区域资源 - 请求 URL 太长
- ruby - Ruby RSpec Net:HTTP - 如何在模拟响应时按预期测试请求有效负载
- python - 在 python 3.8 shared_memory 中,resource_tracker 需要由子进程继承,但这是如何实现的呢?
- flutter - 如何在颤动中创建多色按钮
- c# - 在 Blazor 中是否有更短的方法来完成这项任务?
- c++ - gcore如何处理多线程程序?