【问题标题】:unable to test maxLength with mock input enzyme无法使用模拟输入酶测试 maxLength
【发布时间】:2019-02-05 17:57:12
【问题描述】:

我想为maxLength 测试Input jsx 元素。 我在反应中的元素-

const ValidatedInput = ({ name, labelName, value, onChange, disabled, maxLength = 10 }) => {
    return (
        <div className="form-group">
            <label className="form-control-label" htmlFor={name}>
                {labelName}
            </label>
            <Input className="form-control" type="text" id={name} name={name} value={value} autoComplete="off"
                onChange={onChange}
                disabled={disabled}
                maxLength={maxLength}
            />
        </div>
    )
};

我的测试是

it('should not content more that 10 characters', () => {
        const wrapper = mount(<ValidatedInput onChange={()=> {return true;}}
            id={'testInput'}
            value={'1234567890extra'}
            />);
        expect(wrapper.find('input').instance().value).toBe('1234567890');
});

我在控制台上打印的值是 '1234567890extra' 而不是 '1234567890',而当从 UI 手动测试时,它运行良好。

【问题讨论】:

  • Input 是什么?和input有区别吗?

标签: reactjs mocking enzyme maxlength


【解决方案1】:

代码使用max prop for Input component,而maxlength for input element

doesn't have features to set input values。并且通过value(属性和道具)设置值绕过maxlength 限制,该限制仅用于用户输入。请注意it isn't applied to initial value prop,这证明maxlength 工作方式的假设是错误的。一个值应该被额外限制在存储它的数据库中。

单元测试(Enzyme 用于)的正确方法是不测试内在的浏览器行为或其他库,这应该保存用于 E2E 测试。可以测试ValidatedInputinput 提供了正确的maxlength

expect(wrapper.find('input').prop('maxlength')).toBe(10);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 2016-12-07
    • 2011-09-18
    • 1970-01-01
    相关资源
    最近更新 更多