如何声明属性的呈现值? [英] How to assert an attribute's rendered value?

查看:126
本文介绍了如何声明属性的呈现值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是反应的新手,并看着

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绑定正确. labelReactComponent,我看到许多可用的属性和方法.查看和测试将要呈现的实际值的最佳方法是什么?

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.

这篇关于如何声明属性的呈现值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆