【问题标题】:How to test child props without triggering "Do not access .props of a DOM node" (0.14)?如何在不触发“不访问 DOM 节点的 .props”(0.14)的情况下测试子道具?
【发布时间】:2015-11-09 17:14:48
【问题描述】:

我有一个组件,它的工作是为其子组件添加某些属性:

const Parent = React.createClass({
  doStuff() {
    // ...
  },

  render() {
    const child = React.cloneElement(this.props.children, {doStuff: this.doStuff});
    return <div>{child}</div>;
  }
});

使用 0.13 我可以像这样测试它:

const {renderIntoDocument, findRenderedDOMComponentWithClass} = TestUtils;

const parent = renderIntoDocument(<Parent><span className="test" /></Parent>);
const child = findRenderedDOMComponentWithClass(parent, "test");

expect(child.props.doStuff).to.equal(parent.doStuff);

测试这个的“0.14方式”是什么?

PS。我在其他地方测试了 Parent.doStuff 的行为,但我还需要确保给定的孩子获得对该方法的引用。

PPS。我阅读了How to check props of a DOM node in an unit test in React 0.14?,但它不适用于我的问题,因为我没有测试可以使用domNode.getAttribute() 阅读的道具。

【问题讨论】:

    标签: unit-testing reactjs tdd


    【解决方案1】:

    我终于明白了。这是现在对我有用的方法(Parent 是被测单元):

    const TestChild = () => <div />;
    
    const TestContainer = React.createClass({
      getParent() {
        return this.refs.parent;
      },
    
      getChild() {
        return this.refs.testChild;
      },
    
      render() {
        return <Parent ref="parent"><TestChild ref="testChild" /></Parent>;
      }
    });
    
    const {renderIntoDocument, findRenderedDOMComponentWithClass} = TestUtils;
    
    const testContainer = renderIntoDocument(<TestContainer />);
    const parent = testContainer.getParent();
    const child = testContainer.getChild();
    
    expect(child.props.doStuff).to.equal(parent.doStuff);
    

    TestChild 必须是自定义组件,否则this.refs.testChild 只会返回 DOM 节点而不是组件实例。

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 2012-02-13
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多