1

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?

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132

1 Answers1

2

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.

Anders Ekdahl
  • 22,685
  • 4
  • 70
  • 59
  • Thanks, I think this is my issue. Seems strange that the "syntax issue" renders fine in a browser. – Davin Tryon Apr 27 '15 at 06:59
  • Well, it's not a syntax error really, my mistake for phrasing it that way. It's just valid code inside a string, and there's no way for the Javascript engine to know that it's code and not a string (remember that everything inside { and } in JSX is just Javascript). – Anders Ekdahl Apr 27 '15 at 07:19
  • Thank you. I guess that makes sense. There *must* be some way for react to know, however, because it renders fine in the browser :). If there was no way to know then I'd expect to see `{this.props.targetName}` rendered. I've now checked and this was indeed causing the issue. So, thanks very much for your help. – Davin Tryon Apr 27 '15 at 08:08