【问题标题】:React/enzyme - How to test reference functionReact/enzyme - 如何测试参考函数
【发布时间】:2019-02-25 15:42:06
【问题描述】:

我有一个组件,其中包含已将功能分配给 ref 的输入,我尝试为它编写测试:

 <input
   id="input-element"
   type="checkbox"
   checked={isChecked}
   ref={(input) => {
       if (input) {
           input.indeterminate = true;
       }
   }}
   className="checkbox" />

我的问题是如何检查输入不确定是否设置为真。文档https://airbnb.io/enzyme/docs/api/ReactWrapper/ref.html 对我没有帮助,因为只有非常简单和无用的示例。

我尝试过这样测试:

const wrapper = shallow(<MyComponent {...props}/>);
expect(wrapper.find('#input-element').prop('indeterminate')).toBeTruthy();

但是wrapper.find('#input-element').prop('indeterminate') 回复我undefined

【问题讨论】:

    标签: javascript reactjs enzyme


    【解决方案1】:

    来自酶 github:

    您可能已经注意到 ShallowRenderer 没有 ref() 方法的文档,而 MounedRenderer 有。如果你想测试 refs,你必须挂载。

    我相信原因是浅渲染不维护内部实例,因此它不能保存引用。这就是浅渲染的目的。甚至 FB ReactTestUtils shallowRendering 也不适用于 refs。

    https://github.com/airbnb/enzyme/issues/316

    您需要使用mount 而不是shallowMount

    也可以在这里查看:

    https://airbnb.io/enzyme/docs/api/ReactWrapper/ref.html

    【讨论】:

      【解决方案2】:

      也许你可以这样尝试: 当您编写更复杂的代码时,您还需要编写复杂的测试,希望这对您有所帮助。

      handle = (e) => {
         // indeterminate = true;
         // whatever you what to do
      }
      
      <input
         id="input-element"
         type="checkbox"
         checked={isChecked}
         ref="inputRef"
         onChange={() => 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();
      

      【讨论】:

        【解决方案3】:

        根据the React docs section on Callback Refs,“React 会在组件挂载时调用带有 DOM 元素的 ref 回调”。

        shallow 不会进行完整的 DOM 渲染,因此永远不会挂载组件并且永远不会调用 Callback Ref。为确保调用回调 Ref,您需要使用 mount 进行完整的 DOM 渲染。

        Starting with v2.7 Enzyme 提供ReactWrapper.getDOMNode 作为Full DOM Rendering API 的一部分。

        您可以将mountReactWrapper.getDOMNode 结合使用来访问DOM 节点并测试indeterminate,如下所示:

        const wrapper = mount(<MyComponent {...props} />);
        expect(wrapper.find('#input-element').first().getDOMNode().indeterminate).toBeTruthy();  // SUCCESS
        

        【讨论】:

        【解决方案4】:

        如果您关心的只是测试 ref 设置回调而不是 ref 组件本身,我已经找到了一种方法来通过模拟 ref 来使用 shallow 呈现的组件:

        const mockRef = {};
        const wrapper = shallow(<MyComponent/>);
        const inputElement = wrapper.find('#input-element');
        inputElement.getElement().ref(mockRef)
        expect(mockRef.indeterminate).toEqual(true);
        

        【讨论】:

        • 这实际上适用于测试 REF 分配并避免安装组件。谢谢。
        猜你喜欢
        • 2018-06-13
        • 2018-11-01
        • 2018-10-31
        • 1970-01-01
        • 2018-10-20
        • 2019-02-03
        • 2021-01-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多