简体   繁体   English

模拟酶中的onClick事件

[英]Simulate onClick event in enzyme

I have this code in my Search component render method: 我的Search组件render方法中有以下代码:

   <button className="searchButton" onClick={this.handleSearch}>{this.state.on ? 'Search' : null}</button>

and then I have this: 然后我有这个:

  handleSearch = (e) => {
    this.setState(prevState => ({
      on: !prevState.on
    }));
  }

this definitely gets called when I click the button. 当我单击按钮时,这肯定会被调用。 however, my test is not simulating it even though I feel like I am doing it the correct way. 但是,即使我觉得自己以正确的方式进行测试,我的测试也不是模拟它。

it.only('calls handleSearch', () => {
  searchButton = renderedOutput.find('button').at(0);
  searchButton.simulate('click');
  expect(handleSearchStub).to.have.been.called;
});

however, for some reason it does not think that my function has been called even though surely that is the way to simulate it? 但是,由于某种原因,即使可以肯定地模拟了我的函数,也不会认为我的函数已被调用? (there is only one button on the page) (页面上只有一个按钮)

The problem here is enzyme considers handle search method as a constant. 这里的问题是酶将手柄搜索方法视为一个常数。 Try something like this. 尝试这样的事情。 it should work 它应该工作

handleSearch(e){
    this.setState(prevState => ({
      on: !prevState.on
    }));
  }

 <button className="searchButton" onClick={(e) => this.handleSearch(e)}>{this.state.on ? 'Search' : null}</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM