无法为按钮单击事件编写单元测试用例

时间:2019-04-26 06:03:50

标签: javascript reactjs

我正在研究React JS应用程序。每当用户按下Enter键时,我都会触发以下事件。

dispatchSearch() {
    if (!this.isSearchButtonDisabled()) {
      const searchTerms = { [this.state.searchType]: this.state.searchTerm };
      const searchDbTarget = '';
      const options = {};
      this.props.searchParameters(searchTerms, searchDbTarget, options, this.state.allOpenStoresSearchTerms.selectedOption);
    }
  }

上面的代码按预期工作。下面是上面代码的单元测试用例。

 it('should dispatch a keycode when keycode value is set', () => {
    component.setState({ searchTerm: 'some-value', allOpenStoresSearchTerms: {selectedOption: {value: 'true', label: 'Open Stores'}} });
    component.find('SearchInput').props().onKeyPress({ key: 'Enter' });
    expect(dispatchEvent).toBeCalled();
    expect(dispatchEvent).toBeCalledWith({ simsKeycode: 'some-value', allOpenStoresSearchTerms: {selectedOption: {value: 'true', label: 'Open Stores'}} });
  });

此单元测试用例失败,并抛出以下错误

  

预期的模拟函数已被调用:         {“ allOpenStoresSearchTerms”:{“ selectedOption”:{“ label”:“ Open Stores”,“ value”:“ true”}},“ simsKeycode”:“ some-value”}作为参数   1,但使用{“ simsKeycode”:“ some-value”}进行了调用。         未定义为参数2,但使用“”进行了调用。         未定义为参数3,但使用{}进行了调用。         未定义为参数4,但使用{“ label”:“ Open Stores”,“ value”:“ true”}来调用。

我可以知道以上代码中缺少的内容吗?任何帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

setState方法仅在挂载渲染组件时有效。在浅层渲染上不起作用。

相关问题