How to assert an attribute's rendered value?

2019-08-11 19:29发布

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:

Label component:

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;

Jest test:

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}
    });
});

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?

1条回答
The star\"
2楼-- · 2019-08-11 19:59

The problem is that you have a syntax error. This line:

<label htmlFor="{this.props.targetName}">{this.props.content}</label>

Should be:

<label htmlFor={this.props.targetName}>{this.props.content}</label>

Notice that there's no quotes around the attribute value.

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.

查看更多
登录 后发表回答