加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 使用Enzyme和Sinon调用React组件上的测试自定义方法

发布时间:2020-12-15 20:16:31 所属栏目:百科 来源:网络整理
导读:我想检查当我的组件上单击一个按钮时,它会调用我创建的方法来处理点击.这是我的组件: import React,{ PropTypes,Component } from 'react';class Search extends Component { constructor(){ super(); this.state = { inputValue: '' }; } handleChange = (
我想检查当我的组件上单击一个按钮时,它会调用我创建的方法来处理点击.这是我的组件:

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.我已经尝试了很多关于语法的变化,我想也许我只是缺少一些基本的东西.任何帮助将不胜感激.

解决方法

我对Sinon也比较陌生.我一般将spy()传递给组件道具,并检查它们(尽管你可以以相同的方式使用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();
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读