无法使用模拟输入酶测试maxLength [英] unable to test maxLength with mock input enzyme
问题描述
我想测试maxLength
的Input
jsx元素.
我在react-
I want to test Input
jsx element for maxLength
.
My element in react-
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'
&当从UI手动测试时,它不是'1234567890'
,它工作得很好.
I printed value on console it's '1234567890extra'
& not '1234567890'
while when tested manually from UI, it worked perfectly.
推荐答案
该代码对Input
component 使用max
道具,而对于input
则使用maxlength
元素.
The code uses max
prop for Input
component, while it is maxlength
for input
element.
酶没有设置输入值的功能.通过value
(属性和属性)设置值将绕过maxlength
限制,该限制仅用于用户输入.请注意,它不适用于初始的value
道具,这证明了该假设如何maxlength
作品错误.值还应该在存储它的数据库中另外限制.
Enzyme 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, this proves that the assumption how maxlength
works was wrong. A value should be additionally limited in a database where it was stored .
单元测试(酶所针对的)的一种正确方法是不测试内部浏览器的行为或其他库,应将其保存以进行E2E测试.可以使用以下方法测试ValidatedInput
为input
提供了正确的maxlength
:
A proper approach for unit tests (which Enzyme is for) is to not test intrinsic browser behaviour or other libraries, this should be saved for E2E tests. It's possible to test that ValidatedInput
provided correct maxlength
for input
with:
expect(wrapper.find('input').prop('maxlength')).toBe(10);
这篇关于无法使用模拟输入酶测试maxLength的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!