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

只愿长相守 提交于 2019-12-07 07:24:02

问题


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 {

  constructor(){
    super();
    this.state = { inputValue: '' };
  }

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

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

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

  render(){
    return (
      <form>
        <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>
      </form>
    );
  }
}

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() {}     });
      stub.called.should.be.true();
    });

  });

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.


回答1:


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} />)

wrapper.find('button').simulate('click')

methodSpy.called.should.equal(true)

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
  compInstance.forceUpdate()
  shallowWrapper.update()

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

  handleSubmitStub.called.should.be.true();
});


来源:https://stackoverflow.com/questions/39809046/test-custom-method-on-react-component-has-been-called-using-enzyme-and-sinon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!