在React组件的Jest / Enzyme测试中没有调用模拟函数

时间:2018-03-21 04:42:04

标签: reactjs jestjs enzyme antd

我正在尝试使用Jest和Enzyme进行React测试,我正在编写一个简单的测试,当用户在搜索字段中输入文本时,我会验证是否使用正确的参数调用了两个动​​作创建者。用户更改输入会导致onChange和onSearch事件处理程序触发(https://ant.design/components/select/)。

我为每个动作创建者创建了模拟函数,并将它们设置为组件的道具,我浅呈现。问题是模拟函数之一在模拟输入更改时没有调用,即使它在实际应用程序中被调用。

以下是该组件的相关部分:

export class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: '',
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSearch = this.handleSearch.bind(this);
    this.handleSearch = _.debounce(this.handleSearch, 450);
  }

  handleChange(value) {
    this.setState({
      value,
    });
    this.props.setSearchSpinner(true);
  }

  handleSearch(value) {
    this.props.fetchVideos(value);
  }

  render() {
...
...
...
 return (
      <Select
        className="search-bar"
        mode="combobox"
        value={this.state.value}
        style={{ width: '100%', padding: '0 10px' }}
        placeholder={this.props.placeholder}
        defaultActiveFirstOption={false}
        filterOption={false}
        notFoundContent={
          this.state.value !== '' ? 'we got nothin\' for you bruh' : null
        }
        onChange={this.handleChange}
        onSearch={this.handleSearch}
      >
        {results}
      </Select>
    );
  }
}

这是测试:

it("correctly calls fetchVideos with user's input", () => {
  const mockFetchVideos = jest.fn();
  const mockSetVideo = jest.fn();
  const mockSetSearchSpinner = jest.fn();
  const mockSetSearchPage = jest.fn();

  const wrapper = shallow(<SearchBar
    fetchVideos={mockFetchVideos}
    setVideo={mockSetVideo}
    setSearchSpinner={mockSetSearchSpinner}
    setSearchPage={mockSetSearchPage}
    placeholder="placeholder"
    currentResults={[]}
  />);

  const searchVal = 'mario';
  // simulate user typing 'mario' into search bar
  wrapper.find('.search-bar').simulate('change', {value: searchVal});
  // test to see arguments used after search has been submitted
  expect(mockSetSearchSpinner).toHaveBeenCalledWith(true);
  expect(mockFetchVideos).toHaveBeenCalled();
});

测试在最后一行失败,因此看起来没有调用mockFetchVideos。我收到这个错误:

FAIL  src/containers/search-bar.test.js
  ● correctly calls fetchVideos with user's input

    expect(jest.fn()).toHaveBeenCalled()

    Expected mock function to have been called.

      at Object.<anonymous>.it (src/containers/search-bar.test.js:25:27)
          at new Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:160:7)

我还尝试为handleSearch方法创建一个spy,它包含fetchVideos,并测试是否会调用它。它也没有被调用,所以看起来它不是mockFetchVideos的问题,而是改变事件根本不触发handleSearch。我认为它可能与handleSearch被去抖动有关,但删除去抖也不起作用。我错过了什么导致handleSearch不被调用?

0 个答案:

没有答案