问题描述
我是反应的新手,并看着 Jest 作为潜在的单元测试解决方案.但是,我发现很难发现如何简单地在ReactComponent
中声明渲染属性值.我不确定这是因为通常的做法是不渲染并查看实际值,还是我还没有找到一个好的示例.
I'm new to React and looking at Jest as a potential unit testing solution. However, I've found it surprisingly difficult to find out how to simply assert a rendered attribute value in a ReactComponent
. I'm not sure if this is because the usual practice is to not render and see the actual value, or if I've just not found a good example yet.
所以,这就是我正在使用的东西:
So, here is what I'm working with:
标签组件:
var Label = React.createClass({
render: function() {
if (this.props.targetName) {
return (
<label htmlFor="{this.props.targetName}">{this.props.content}</label>
);
}
return (
<label>{this.props.content}</label>
);
}
});
module.exports = Label;
最好的测试:
describe('Label sub component', function() {
var Label = require('../../../views/label');
it('has the correct target element name', function() {
var labelDocument = TestUtils.renderIntoDocument(
<Label targetName="foobar" content="Upload Files:"/>
);
var label = TestUtils.findRenderedDOMComponentWithTag(labelDocument, 'label');
expect(label.getDOMNode().getAttribute('for')).toEqual('foobar'); // actually returns {this.props.targetName}
});
});
因此,如您所见,我不确定这里的期望断言.我希望在正确的元素中呈现值foobar
.然后,我可以确保props
绑定正确. label
是ReactComponent
,我看到许多可用的属性和方法.查看和测试将要呈现的实际值的最佳方法是什么?
So, as you can see, I'm not certain about the expect assertion here. I'd like to expect that the value foobar
is rendered in the correct element. Then, I can make sure that the props
binding is correct. label
is a ReactComponent
and I see many properties and methods available. What is the best way to see and test for the actual value that would be rendered?
推荐答案
问题是您遇到语法错误.这行:
The problem is that you have a syntax error. This line:
<label htmlFor="{this.props.targetName}">{this.props.content}</label>
应该是:
<label htmlFor={this.props.targetName}>{this.props.content}</label>
请注意,属性值周围没有引号.
Notice that there's no quotes around the attribute value.
还请注意,您的label
变量是一个React组件实例,它具有一个props
属性,您可以使用它来代替在DOM节点上查找它.
Also note that your label
variable is a React component instance, which has a props
property that you can use instead of looking it up on the DOM node.
这篇关于如何声明属性的呈现值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!