使用Sinon的Spy进行表单验证时出错

问题描述 投票:0回答:1

我无法使用Sinon的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: '[email protected]' } });
     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;

我可以进行哪些修改才能通过此测试?

reactjs unit-testing sinon spy
1个回答
0
投票

您在isFormValid中的任何地方都不会使用Form。 React并不神奇地知道如何传递给isFormValid构造函数的React.Component(除非您使用的是未提及的神奇库。

不是“ sinon”,它缺乏适当的实现,无法调用isFormValid

至少,您应该在按钮上安装onClick回调,并使用一些值调用此validate,例如:

<button onClick={this.handleSubmit} ...>Verify</button>

onSubmit方法或多或少看起来像这样:

onSubmit = (event) => {
    const valuues = collectValues();
    if (this.props.isFormValid(values)) {
        // ... handle submit
    }
}

[在很多地方都使用形式验证,例如this answer也使用形式HTML5 validation API(虽然不确定酶是否支持)

© www.soinside.com 2019 - 2024. All rights reserved.