Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme returns null for prop on shallow rendered react component

The Issue

I am just getting started with enzyme and react testing. I am trying to get enzyme working with karma and webpack on a trivial react component. My issue is that prop() on the wrapper returns null and I am not sure why.

Greeter.js

import React from 'react';

/*
 * A trivial component we added while trying to get the react testing  working
 * */

export default class Greeter extends React.Component {
constructor(props) {
    super(props);
    this.state = { name: props.initialName };

    this.greeterText = this.greeterText.bind(this);
}

greeterText() {
    return (<p>Hello, {this.state.name}!</p>);
}

render() {
    return (<div className="greeter">
        {this.greeterText()}
    </div>);
  }
}

Greeter.defaultProps = { initialName: "World" };

Greeter.propTypes = {
  initialName: React.PropTypes.string
};

greeter.spec.js

import Greeter from '../../components/test/Greeter';
import React from 'react';
import { shallow } from 'enzyme';


describe("Simple testing with shallow rendering", () => {
  beforeEach(function() {
    let initialName = "joe";
    this.wrapper = shallow(<Greeter initialName={initialName} />);
  });

  it("renders default Greeter", function() {
    console.log(this.wrapper.find(".greeter").text());
    console.log(this.wrapper.debug());
    console.log(this.wrapper.state('name'));
    expect(this.wrapper.state('name')).to.equal("joe");
    expect(this.wrapper.prop('initialName')).to.equal("joe");
   });
 });

Result

Simple testing with shallow rendering × renders default Greeter Chrome 50.0.2661 (Windows 10 0.0.0) AssertionError: expected undefined to equal 'joe' at Assertion.assertEqual >>(F:/web/forms/node_modules/chai/chai.js:776:12) at Assertion.ctx.(anonymous function) [as equal] (F:web/forms/node_modules/chai/chai.js:4192:25) at Context. (F:web/forms/spec/components/greeter.spec.js:9:2932 <- webpack:///spec/components/greeter.spec.js:18:52)

Stack

  • react 0.14.8
  • karma
  • webpack
  • enzyme 2.2.0
like image 412
algernon Avatar asked May 05 '16 23:05

algernon


1 Answers

If you want to test props passed in like that use mount like so:

  it('allows us to set props', () => {
    const wrapper = mount(<Foo bar="baz" />);
    expect(wrapper.props().bar).to.equal("baz");
    wrapper.setProps({ bar: "foo" });
    expect(wrapper.props().bar).to.equal("foo");
  });
like image 145
omarjmh Avatar answered Oct 17 '22 05:10

omarjmh