unable to test maxLength with mock input enzyme

萝らか妹 提交于 2019-12-25 02:15:42

问题


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>
    )
};

My test is

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');
});

I printed value on console it's '1234567890extra' & not '1234567890' while when tested manually from UI, it worked perfectly.


回答1:


The code uses max prop for Input component, while it is maxlength for input element.

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 .

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);


来源:https://stackoverflow.com/questions/52102946/unable-to-test-maxlength-with-mock-input-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!