无法使用模拟输入酶测试 maxLength
unable to test maxLength with mock input enzyme
我想为 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
component使用max
prop,对input
[=29=使用maxlength
]元素.
酶doesn't have features to set input values. And setting the value through value
(both property and prop) bypasses maxlength
restriction, which is intended for user input only. Notice that it isn't applied to initial value
prop,这证明了maxlength
如何工作的假设是错误的。一个值应该被额外限制在存储它的数据库中。
单元测试(Enzyme 适用)的正确方法是不测试固有的浏览器行为或其他库,这应该留作 E2E 测试。可以通过以下方式测试 ValidatedInput
为 input
提供了正确的 maxlength
:
expect(wrapper.find('input').prop('maxlength')).toBe(10);
我想为 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
component使用max
prop,对input
[=29=使用maxlength
]元素.
酶doesn't have features to set input values. And setting the value through value
(both property and prop) bypasses maxlength
restriction, which is intended for user input only. Notice that it isn't applied to initial value
prop,这证明了maxlength
如何工作的假设是错误的。一个值应该被额外限制在存储它的数据库中。
单元测试(Enzyme 适用)的正确方法是不测试固有的浏览器行为或其他库,这应该留作 E2E 测试。可以通过以下方式测试 ValidatedInput
为 input
提供了正确的 maxlength
:
expect(wrapper.find('input').prop('maxlength')).toBe(10);