use*_*ser 3 javascript reactjs enzyme
我有一个包含已将函数分配给 ref 的输入的组件,我尝试为其编写测试:
<input
id="input-element"
type="checkbox"
checked={isChecked}
ref={(input) => {
if (input) {
input.indeterminate = true;
}
}}
className="checkbox" />
Run Code Online (Sandbox Code Playgroud)
我的问题是如果输入不确定设置为 true,如何检查测试。文档https://airbnb.io/enzyme/docs/api/ReactWrapper/ref.html对我没有帮助,因为只有非常简单且无用的示例。
我试着测试一下:
const wrapper = shallow(<MyComponent {...props}/>);
expect(wrapper.find('#input-element').prop('indeterminate')).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)
但wrapper.find('#input-element').prop('indeterminate')归还我undefined
如果您关心的是测试 ref 设置回调而不是 ref 组件本身,我已经找到了一种shallow通过模拟 ref 对渲染组件执行此操作的方法:
const mockRef = {};
const wrapper = shallow(<MyComponent/>);
const inputElement = wrapper.find('#input-element');
inputElement.getElement().ref(mockRef)
expect(mockRef.indeterminate).toEqual(true);
Run Code Online (Sandbox Code Playgroud)