如何在不触发 "Do not access .props of a DOM node" (0.14) 的情况下测试 child 道具?
How to test child props without triggering "Do not access .props of a DOM node" (0.14)?
我有一个组件,其工作是向其添加某些属性 child:
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 的行为,但我还需要确保给定的 child 获得对此方法的引用。
PPS。我读了 How to check props of a DOM node in an unit test in React 0.14? 但它不适用于我的问题,因为我没有测试我可以用 domNode.getAttribute()
.
阅读的道具
终于明白了。这是现在对我有用的(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
只有 returns 一个 DOM 节点而不是组件实例。
我有一个组件,其工作是向其添加某些属性 child:
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 的行为,但我还需要确保给定的 child 获得对此方法的引用。
PPS。我读了 How to check props of a DOM node in an unit test in React 0.14? 但它不适用于我的问题,因为我没有测试我可以用 domNode.getAttribute()
.
终于明白了。这是现在对我有用的(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
只有 returns 一个 DOM 节点而不是组件实例。