【问题标题】:Expected mock function to have been called But it was not called预期的模拟函数已被调用但未被调用
【发布时间】:2019-03-28 06:11:48
【问题描述】:

我有一个测试,只是想看看是否调用了 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,一切似乎都很好......

不确定这里发生了什么,这让我发疯了。 谢谢

【问题讨论】:

  • 您是否尝试仅使用 toHaveBeenCalled 来检查参数是否存在问题而不是 fn 调用?
  • @Diljohn5741我做到了。一样的

标签: reactjs unit-testing jasmine enzyme


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2018-12-27
    • 1970-01-01
    • 2018-05-25
    • 2019-10-27
    • 1970-01-01
    • 2019-07-21
    • 2019-03-23
    • 2023-03-24
    相关资源
    最近更新 更多