Testing changes to React component state and spying on instance methods using enzyme
<p>I am working on a wrapper component for smoothly loading images in React. I use enzyme with mocha, chai and sinon to unit test my component. In the test here, I am trying to test that the:</p>

<ol>
<li><p>component's state is updated when the image has loaded</p></li>
<li><p>the <code>onLoad</code> instance method on the component was called</p></li>
</ol>

<pre>
const wrapper = shallow( );

const onLoad = wrapper.find('img').props().onLoad;
const onLoadSpy = sinon.spy(onLoad); wrapper.update();
const status = wrapper.state().status;
expect(onLoadSpy).to.have.been.called;
expect(status).to.equal('LOADED');
</pre>

<p>I find that neither the update to the state is reflected by enzyme or the call count of the <code>onLoad</code> spy is updated. This is the corresponding code for the test:</p>

<pre><code>export default class Image extends Component {
  constructor(props) {
    super(props);
    if (props.src != null &amp;&amp; typeof props.src === 'string') {
      this.state = {
        status: LOADING,
      };
    } else {
      this.state = {
        status: PENDING,
      };
    }
    this.onLoad = this.onLoad.bind(this);
  }

  onLoad() {
    this.setState({
      status: LOADED,
    });
  }

  render() {
    //lots of code above the part we care about
    const defaultImageStyle = style({
      opacity: 0,
      transisition: 'opacity 150ms ease',
    });

    const loadedImageStyle = style({
      opacity: 1,
    });

    let imageStyle = defaultImageStyle;

    if (this.state.status === LOADED) {
      imageStyle = merge(defaultImageStyle, loadedImageStyle);
    } else {
      imageStyle = defaultImageStyle;
    }


    let image;
    if (alt != null) {
      image = (&lt;img
        className={imageStyle}
        src={src}
        width={width}
        height={height}
        alt={alt}
        onLoad={this.onLoad}
      /&gt;);
    } else {
      image = (&lt;img
        className={imageStyle}
        src={src}
        width={width}
        height={height}
        role="presentation"
        onLoad={this.onLoad}
      /&gt;);
    }

    let statusIndicator = null;
    if (this.state.status === LOADING) {
      statusIndicator = (&lt;div className={loadingStyle}&gt;&lt;/div&gt;);
    }

    return (&lt;div className={wrapperStyle}&gt;
      {statusIndicator}
      {image}
    &lt;/div&gt;);

    }}
</code></pre>

<p>To take a look at the full code for better context:</p>

<ul>
<li><p>the <a href="https://github.com/vamsiampolu/css-in-js-test/blob/glamor/app/Image.js" rel="noreferrer">source here</a></p></li>
<li><p>the <a href="https://github.com/vamsiampolu/css-in-js-test/blob/glamor/test/Image.js" rel="noreferrer">test here</a></p></li>
</ul>