Javascript 反应/酶-如何测试参考功能
我有一个组件,其中包含已将函数分配给ref的输入,我尝试为其编写测试:Javascript 反应/酶-如何测试参考功能,javascript,reactjs,enzyme,Javascript,Reactjs,Enzyme,我有一个组件,其中包含已将函数分配给ref的输入,我尝试为其编写测试: <input id="input-element" type="checkbox" checked={isChecked} ref={(input) => { if (input) { input.indeterminate = true; } }} className="checkbox" /> { 如果(输入){
<input
id="input-element"
type="checkbox"
checked={isChecked}
ref={(input) => {
if (input) {
input.indeterminate = true;
}
}}
className="checkbox" />
{
如果(输入){
input.Undeterminate=true;
}
}}
className=“复选框”/>
我的问题是,如果输入不确定设置为true,如何检入测试。文档对我没有帮助,因为只有非常简单和无用的示例
我试着这样做:
const wrapper = shallow(<MyComponent {...props}/>);
expect(wrapper.find('#input-element').prop('indeterminate')).toBeTruthy();
const wrapper=shallow();
expect(wrapper.find('#input element').prop('indeterminate')).toBeTruthy();
但是wrapper.find('#input element').prop('indeterminate')
从以下位置返回我未定义的:
您可能已经注意到ShallerRenderer没有ref()方法的文档,而MouedRenderer有。如果要测试引用,必须安装
我认为原因是浅层渲染不维护内部实例,因此它不能保存引用。这就是浅层渲染的目的。即使FB ReactTestUtils变浅也不适用于裁判
您需要使用mount
而不是shallowMount
请在此查看:
也许你可以这样尝试:
当您编写更复杂的代码时,您还需要编写复杂的测试,我希望这对您有所帮助
handle = (e) => {
// indeterminate = true;
// whatever you what to do
}
<input
id="input-element"
type="checkbox"
checked={isChecked}
ref="inputRef"
onChange={() => this.handle()}
className="checkbox">
handle=(e)=>{
//不确定=真;
//不管你做什么
}
this.handle()}
className=“checkbox”>
测试代码
const wrapper = shallow(<MyComponent {...props}/>);
const inputElement = wrapper.find('#input-element').prop();
expect(inputElement.ref).toEqual("inputRef");
inputElement.onClick();
// your condition I'm not sure
// expect(indeterminate).toBeTruthy();
const wrapper=shallow();
const inputElement=wrapper.find('#input element').prop();
expect(inputElement.ref).toEqual(“inputRef”);
inputElement.onClick();
//你的情况我不确定
//expect(不确定)。toBeTruthy();
根据“组件装载时,React将使用DOM元素调用ref回调”
shallow
不会进行完整的DOM渲染,因此永远不会装入组件,也不会调用回调引用。要确保调用回调Ref,需要使用mount
执行完整的DOM渲染
酶
作为酶的一部分提供
您可以将mount
与ReactWrapper.getDOMNode
结合使用,以获得对DOM节点的访问权限,并测试不确定
,如下所示:
const wrapper=mount();
expect(wrapper.find('#input element').first().getDOMNode().indeterminate.toBeTruthy();//成功
如果您关心的只是测试ref设置回调,而不是ref组件本身,那么我已经找到了一种方法,通过模拟ref来使用浅层
渲染组件来实现这一点:
const mockRef = {};
const wrapper = shallow(<MyComponent/>);
const inputElement = wrapper.find('#input-element');
inputElement.getElement().ref(mockRef)
expect(mockRef.indeterminate).toEqual(true);
const mockRef={};
常量包装器=浅();
const inputElement=wrapper.find('#input element');
inputElement.getElement().ref(mockRef)
expect(mockRef.不确定)。toEqual(真);
这实际上适用于测试REF分配,并避免安装组件。谢谢。有没有办法测试useLayoutEffect,试过使用shallow和mount没有任何建议?