使用Enzyme和Sinon调用了对React组件的测试自定义方法

使用Enzyme和Sinon调用了对React组件的测试自定义方法

问题描述:

我想检查单击组件上的按钮时是否调用了我创建的用于处理单击的方法.这是我的组件:

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;

这是我的考试

  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();
    });

  });

被叫属性的调用返回false.我已经尝试了语法上的各种变化,并且我想也许我只是缺少一些基本知识.任何帮助将不胜感激.

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.

我对Sinon还是比较陌生.通常,我一直在将spy()传递到组件props中,并进行检查(尽管您可以以相同的方式使用stub()):

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();
});