vijayst vijayst - 3 months ago 22
React JSX Question

Testing react component with enzyme and expect fails

I am testing a React component with Enzyme, Mocha, and Expect. The test case is shown below:

import React from 'react';
import expect from 'expect';
import { shallow } from 'enzyme';
import Add from '../src/client/components/add.jsx';

describe('Add', () => {
let add;
let onAdd;

before(() => {
onAdd = expect.createSpy();
add = shallow(<Add onAdd={onAdd} />);
});

it('Add requires onAdd prop', () => {
console.log(add.props());
expect(add.props().onAdd).toExist();
});

});


I am creating a spy using expect and attaching it to the onAdd prop of the Add component. My test checks if the prop exists on the component. For some reason, onAdd is undefined and the test fails. Any help?

Answer

The problem is that add isn't wrapping the <Add> component, it wraps what it returns. So, if your component looks like:

class Add extends React.Component {
  render() {
    return (
      <div>
        {this.props.foo}
      </div>
    );
  }
}

This statement add.props().onAdd will try to access onAdd prop from <div> not from <Add>, and obviously it will fail.

This assertion:

expect(add.props().onAdd).toExist();

Will succeed, in the component will look like:

class Add extends React.Component {
  render() {
    return (
      <div onAdd={this.props.onAdd}>
        {this.props.foo}
      </div>
    );
  }
}

Example shown in enzyme docs, is a little bit confusing.