jest: Failing to mock a method called with a event listener in React/JSX

When a method is called with an event listener in a React component, the original method is always called and not the mocked one.

// component.jsx

/** @jsx React.DOM */
'use strict';

var React = require('react/addons');

var MyComponent = React.createClass({
    getInitialState: function() {
        return {
            clicked: false
        };
    },
    onButtonClick: function() {
        this.setState({
            clicked: true
        });
    },
    render: function() {
        return (
            <button onClick={this.onButtonClick}>My Button</button>
        );
    }
});

module.exports = MyComponent;
// __tests__/component-test.js

'use strict';

jest.dontMock('../component.jsx');

describe('Component', function() {
    it('must call onButtonClick on click', function() {
        var React = require('react/addons');
        var MyComponent = require('../component.jsx');
        var TestUtils = React.addons.TestUtils;
        var myComponent = TestUtils.renderIntoDocument(<MyComponent />);

        myComponent.onButtonClick = jest.genMockFunction();

        var button = TestUtils.findRenderedDOMComponentWithTag(myComponent, 'button');

        TestUtils.Simulate.click(button);

        expect(myComponent.onButtonClick.mock.calls.length).toBe(1);
        expect(myComponent.state.clicked).toEqual(false);
    });
});

Output:

$ npm test

> jest-bug@1.0.0 test /Users/ycroissant/Workspace/jest-bug
> jest

Using Jest CLI v0.2.1
 FAIL  __tests__/component-test.js (0.566s)
● Component › it must call onButtonClick on click
  - Expected: 0 toBe: 1
        at Spec.<anonymous> (/Users/ycroissant/Workspace/jest-bug/__tests__/component-test.js:19:53)
        at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
  - Expected: true toEqual: false
        at Spec.<anonymous> (/Users/ycroissant/Workspace/jest-bug/__tests__/component-test.js:20:37)
        at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
1 test failed, 1 test passed (2 total)
Run time: 4.614s
npm ERR! Test failed.  See above for more details.

In this example the mock were not called and the original method updated the state. But it works if I call directly myComponent.onButtonClick (the mock is called and not the original method).

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 23 (5 by maintainers)

Commits related to this issue

Most upvoted comments

Yes, the recommended solution is to do MyClass.prototype.myFn = jest.fn().

Facing the same issue… 25 days and still no solution?

I think

LoginForm.prototype.handleSubmit = jest.genMockFunction();

should work. We don’t have plans to change how createClass works here, but you should be able to mock plain-class functions like this without trouble.