Andy Briggs Andy Briggs - 1 year ago 115
React JSX Question

Test custom method on React component has been called, using Enzyme and Sinon

I want to check that when a button is clicked on my component, it calls the method I have created to handle the click. Here is my component:

import React, { PropTypes, Component } from 'react';

class Search extends Component {

this.state = { inputValue: '' };

handleChange = (e) => {
this.setState({ inputValue: });

handleSubmit = (e) => {
return this.state.inputValue;

getValue = () => {
return this.state.inputValue;

return (
<label htmlFor="search">Search stuff:</label>
<input id="search" type="text" value={this.state.inputValue} onChange={this.handleChange} placeholder="Stuff" />
<button onClick={this.handleSubmit}>Search</button>

export default Search;

and here is my test

import React from 'react';
import { mount, shallow } from 'enzyme';
import Search from './index';
import sinon from 'sinon';

describe('Search button', () => {

it('calls handleSubmit', () => {
const shallowWrapper = shallow(<Search />);
const stub = sinon.stub(shallowWrapper.instance(), 'handleSubmit');
shallowWrapper.find('button').simulate('click', { preventDefault() {} });;


The call called property comes back false. I have tried loads of variation on the syntax and I think maybe I'm just missing something fundamental. Any help would be greatly appreciated.

Answer Source

I'm relatively new to Sinon as well. I have generally been passing spy()s into component props, and checking those (though you can use stub() in the same way):

let methodSpy = sinon.spy(),
  wrapper = shallow(<MyComponent someMethod={methodSpy} />)



I point this out because I think it's the most straightforward way to unit test components (testing internal methods can be problematic).

In your example, where you're trying to test internal methods of a component, this wouldn't work. I came across this issue, though, which should help you out. Try:

it('calls handleSubmit', () => {
  const shallowWrapper = shallow(<Search />)
  let compInstance = shallowWrapper.instance()

  let handleSubmitStub = sinon.stub(compInstance, 'handleSubmit');
  // Force the component and wrapper to update so that the stub is used

  shallowWrapper.find('button').simulate('click', { preventDefault() {} });;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download