3

Using basic test-utils and jasmine for unit testing.

How do you spy on a function inside a react component?

test.js:

class Test extends React.Component {
  handleClick() {
    // Do something
  }

  render() {
    return (
      <div className="test-class" onClick={this.handleClick}>Test</div>
    );
  }
}

const React = require('react-with-addons');
const RequireJsTest = require('requirejs-test');
const Utils = React.addons.TestUtils;
const Test = require('./test');

describe('test', () => {
  it('should test', function() {
    const test = Utils.renderIntoDocument(<Test/>);
    const el = Utils.findRenderedDOMComponentWithClass(test, 'test-class');
    spyOn(test, 'handleClick');
    Utils.Simulate.click(el);

    expect(test.handleClick).toHaveBeenCalled();
  });
});

I'm getting the following error:

Expected spy handleClick to have been called. (1)

Any ideas? Thanks!

Jshoe523
  • 3,851
  • 2
  • 18
  • 21

1 Answers1

1

To be honest, I haven't tested react apps yet, but try the method (the last test in describe block), which I've just found in enzyme readme doc.

I think you should spy on component class prototype method before rendering component:

spyOn(Test.prototype, 'handleClick');
// and then
expect(Test.prototype.handleClick).toHaveBeenCalled();
GProst
  • 9,229
  • 3
  • 25
  • 47