首页 > 解决方案 > 预期的模拟函数已被调用但未被调用

问题描述

我有一个测试只是想看看是否调用了 onSearch。

it("calls the onSearch method when searching", () => {
    const testFilter = {
      filterIndex: "testFilter4",
      searchResults: [],
      selectedItems: [],
      isComplete: false,
      isSearchMultiSelect: true,
      entity: "Organization"
    };
    const spy = jest.fn();
    const component = shallow(
      <FilterSelect
        {...preloadedState.main}
        filter={testFilter}
        onSearch={spy}
      />
    );
    component.find("Select").simulate("search", "term1");
    expect(spy).toHaveBeenCalledWith("Organization", "testFilter4", "term1");
  });

我收到此错误:

expect(jest.fn()).toHaveBeenCalledWith(expected)

    Expected mock function to have been called with:
      ["Organization", "testFilter4", "term1"]
    But it was not called.

这里也是“组件”的json

{ node:
         { nodeType: 'class',
           type:
            { [Function: Select]
              Option: [Function],
              OptGroup: [Function],
              defaultProps: [Object],
              propTypes: [Object],
              contextTypes: [Object] },
           props:
            { showSearch: true,
              placeholder: 'Select',
              value: [],
              onSelect: [Function: onSelect],
              disabled: false,
              notFoundContent: 'No results found',
              filterOption: false,
              onSearch: [Function: onSearch],
              children: [],
              prefixCls: 'ant-select',
              transitionName: 'slide-up',
              choiceTransitionName: 'zoom' },
           key: undefined,
           ref: null,
           instance: null,
           rendered: [] },
        type: 'Select',
        props:
         { showSearch: true,
           placeholder: 'Select',
           value: [],
           onSelect: [Function: onSelect],
           disabled: false,
           notFoundContent: 'No results found',
           filterOption: false,
           onSearch: [Function: onSearch],
           prefixCls: 'ant-select',
           transitionName: 'slide-up',
           choiceTransitionName: 'zoom' },
        children: null,
        '$$typeof': Symbol(react.test.json) }

这里还有 Select 的 onSearch 部分:

onSearch={term => {
          this.handleSearch(filter.entity, filter.filterIndex, term);
        }}

透过浅层的 Json 'Select' 并有 onSearch,一切似乎都很好......

不知道这里发生了什么,它让我发疯。谢谢

标签: reactjsunit-testingjasmineenzyme

解决方案


有一个去抖动阻止此测试运行。

这修复了它: https ://gist.github.com/apieceofbart/d28690d52c46848c39d904ce8968bb27


推荐阅读