【问题标题】:Access instance methods in a component wrapped in a Higher Order Component - React.js访问包装在高阶组件中的组件中的实例方法 - React.js
【发布时间】:2015-09-23 23:31:43
【问题描述】:

我正在为我的 React 组件编写一些测试:

let DebugElement = TestUtils.renderIntoDocument(<Debug />);
console.log(DebugElement)
spyOn(DebugElement, 'fetchAndSelect');

但是,它说fetchAndSelect 不存在。这是真的。

我像这样包装我的组件:

import { DragDropContext } from 'react-dnd';

const Debug = React.createClass({
     fetchAndSelect() {}
});

export default DragDropContext(HTML5Backend)(Debug);

如果你看下面的截图,你可以看到我可以在refs.child 中访问我的组件方法。这是正确的方法吗?

【问题讨论】:

    标签: javascript testing reactjs jasmine


    【解决方案1】:

    封装的组件实例是通过getDecoratedComponentInstance()提供的:

    let tree = TestUtils.renderIntoDocument(<Debug />);
    let DebugElement = tree.getDecoratedComponentInstance();
    console.log(DebugElement);
    spyOn(DebugElement, 'fetchAndSelect');
    

    您也可以通过DecoratedComponent对已包装的组件类型访问原始的、未包装的组件type,您可以使用TestUtils.findRenderedComponentWithType或其他方法找到该组件:

    let tree = TestUtils.renderIntoDocument(<Debug />);
    let DebugElement = TestUtils.findRenderedComponentWithType(
      tree, Debug.DecoratedComponent
    );
    console.log(DebugElement)
    spyOn(DebugElement, 'fetchAndSelect');
    

    查看Testing docs 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2018-11-18
      • 1970-01-01
      相关资源
      最近更新 更多