【问题标题】:Test custom method on React component has been called, using Enzyme and Sinon使用 Enzyme 和 Sinon 调用了 React 组件上的测试自定义方法
【发布时间】:2017-02-10 01:35:42
【问题描述】:

我想检查当在我的组件上单击按钮时,它会调用我创建的方法来处理单击。这是我的组件:

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

  });

调用属性返回错误。我已经尝试过大量的语法变化,我想也许我只是错过了一些基本的东西。任何帮助将不胜感激。

【问题讨论】:

    标签: reactjs mocha.js enzyme should.js


    【解决方案1】:

    我对诗乃也比较陌生。我通常将spy()s 传递给组件道具,并检查它们(尽管您可以以相同的方式使用stub()):

    let methodSpy = sinon.spy(),
      wrapper = shallow(<MyComponent someMethod={methodSpy} />)
    
    wrapper.find('button').simulate('click')
    
    methodSpy.called.should.equal(true)

    我指出这一点是因为我认为这是对组件进行单元测试的最直接的方法(测试内部方法can be problematic)。

    在您的示例中,您尝试测试组件的内部方法,这是行不通的。不过,我遇到了this issue,这应该可以帮助您。试试:

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

    【讨论】:

    • 第二个代码 sn-p 确实通过了我的测试。关于测试内部方法的有趣文章,我不知道。一般来说,我对 TDD 相当陌生,所以如果我应该测试的内容不正确,也许我的理解是不正确的。非常感谢,我会坚持我的研究!
    • 对于“单元”的边界应该是什么有不同的看法,我认为您的方法不一定是错误的。但我想我应该把它传递下去,因为这是一个普遍持有的观点。享受您的测试之旅:)
    • 非常感谢,它对我帮助很大,我检查了很多关于酶回购的问题,但它不适用于组件的内部方法。
    • 将近一年后,这个答案救了我。谢谢!
    猜你喜欢
    • 2021-02-22
    • 1970-01-01
    • 2021-06-07
    • 2019-08-31
    • 2017-04-13
    • 2021-06-24
    • 1970-01-01
    • 2017-02-12
    • 2016-01-21
    相关资源
    最近更新 更多