如何测试输入组件是否为只读(readOnly),使用React/Enzyme。

3
我在React中设计了一个组件,包含一个输入字段,该字段只能被设置且必须是只读的,但我无法弄清如何在Enzyme中测试此输入是否为只读。
我找不到有关readOnly属性的任何信息,但有人提出了类似的问题:测试输入是否被禁用。从这个问题来看,似乎我需要使用像下面代码一样的内容。
test('select button select input must be read only', () => {
    expect(select.find('div').find('div').find('input').hasAttribute('readOnly', 'true').toBeTruthy();
});

然而,hasAttribute 在类型ShallowWrapper上不被识别,链接中的其他方法也不能转换/工作/被识别。

只是为了澄清,我的输入字段如下。

<input readOnly={true} type="text" placeholder={selectedOption} />

有人遇到过这个问题吗?我该如何使用Enzyme测试此输入是否为只读?

2个回答

5

由于测试的是组件而不是React将其呈现给DOM的方式,因此它可以:

expect(shallow(<Comp/>).find('div div input').prop('readOnly')).toBe(true);

搞定了,谢谢!同时也解决了我关于属性(如占位符等)的其他问题... - James Morrison

2
在HTML DOM中,属性为readonly,在React DOM中属性为readOnly。可使用readonly='true'readonly来使输入框不可编辑。
例如HTML代码: <input type="text" name="country" value="Norway" readonly> 因此,您的测试代码需要检查: expect(select.find('div').find('div').find('input').hasAttribute('readonly', 'true').toBeTruthy();

类型 ShallowWrapper 上未识别 hasAttribute。 - James Morrison

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接