ffxsam
ffxsam

Reputation: 27793

What's wrong with my Enzyme/Mocha test?

React component:

import React, { Component, PropTypes } from 'react';

export default class Simple extends Component {
  render() {
    return <div className="Simple">
      Result: {this.props.value * 4}
    </div>
  }
}

Simple.propTypes = {
  value: PropTypes.number,
};

Test:

describe('<Simple />', _ => {
  it('should display', done => {
    const wrapper = shallow(<Simple />);

    expect(wrapper.find('div.Simple')).to.have.length(1);
    done();
  });

  it('should quadruple a value passed into it', done => {
    const wrapper = shallow(<Simple value={3} />);

    expect(wrapper.contains(<div className="Simple">Result: 12</div>)).to.equal(true);
    done();
  })
});

The first test passes, the second (quadruple a value) fails. I can't figure out what I'm doing wrong here.

EDIT:

If I modify the component to just return this:

return <div className="Simple">
  Result:
</div>

And the test as follows:

expect(wrapper.contains(
  <div className="Simple">
    Result:
  </div>
)).to.equal(true);

Then it passes. So it's when I introduce calculating props that the test fails. I'm not really sure why.

Upvotes: 1

Views: 927

Answers (1)

Jack Allan
Jack Allan

Reputation: 15014

This works:

  it('should quadruple a value passed into it', done => {
    const wrapper = shallow(<Simple value={3} />);

    expect(wrapper.contains(<div className="Simple">Result: {12}</div>)).to.equal(true);
    done();
  })

This is because there are two child elements in the div. You can see this if you use console.log(wrapper.find('div').childAt(1).text()) this gives you 12.

shallow is basically a wrapper for the shallow renderer from react-addons-test-utils. What this does is execute your components render method and returns the resulting react elements. In this case react would create two elements one for Result: and one for 12. Dan Abramov has an excellent post that describes exactly a react element is.

In your test that didn't work you were looking for a div with one text node but what was rendered was a div with two text nodes. By putting 12 in curly braces you have forced it into a new text node

Upvotes: 2

Related Questions