【问题标题】:Form validation using Spy by Sinon gets wrongSinon 使用 Spy 进行表单验证出错
【发布时间】:2026-02-10 01:50:02
【问题描述】:

我无法使用 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: '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;

为了通过这个测试,我可以修改什么?

【问题讨论】:

    标签: reactjs unit-testing sinon spy


    【解决方案1】:

    您不会在Form 的任何地方使用isFormValid。 React 不知道如何处理传递给React.Component 构造函数的isFormValid(除非你使用了一些你没有提到的神奇库。

    这不是“sinon”,而是缺乏正确的实现调用isFormValid

    至少,您应该在按钮上安装onClick 回调并使用一些值调用此验证,如下所示:

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

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

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

    有很多地方使用表单验证,比如this answer,它也使用表单HTML5 validation API(虽然不确定酶是否支持它)

    【讨论】: