jestjs - Promise.resolve 从 Jest 模拟函数返回未定义

标签 jestjs enzyme

我有一个调用 API 的函数,它会根据第一次 API 调用返回的内容进行第二次 API 调用。但是第一个 API 总是返回 undefined

getTotalCount = async () => {
    const { showCountCallBack, showCount } = this.props;
    try {
      const response = await showCount();

      const count = isEmpty(response.result);

      if (count) {
        console.log(" success");
      } else {
        showCountCallBack({ ...this.state });
      }
    } catch (e) {
      console.log("error");
    }
  };

describe("component", () => {
  let shallowComponent;
  let shallowComponentInstance;
  const showCountMock = jest.fn(() => Promise.resolve({ result: [] }));

  const showCountCallBackMock = jest.fn(() => Promise.resolve({ result: [] }));

  beforeEach(() => {
    showCountMock.mockReset();

    shallowComponent = shallowWithTheme(
      <Component
        showCount={showCountMock}
        showCountCallBack={showCountCallBackMock}
      />
    );
    shallowComponentInstance = shallowComponent.instance();
  });

  it("viewMapping", () => {
    shallowComponentInstance.getTotalCount();
    expect(showCountMock).toHaveBeenCalledTimes(1);
    expect(showCountCallBackMock).toHaveBeenCalledTimes(1);
  });
});

最佳答案

经过几个小时的挣扎。我找到了原因。是 mockReset 导致了这个问题。

它也重置了返回值。所以我只是从代码中删除了 mockReset。最好在这里使用 mockClear

关于jestjs - Promise.resolve 从 Jest 模拟函数返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56472512/

相关文章:

reactjs - Jest - 在 useEffect Hook 中测试clearTimeout

javascript - 模拟 Div 点击 Enzyme 和 React

reactjs - Jest TypeError : e. preventDefault 不是函数

javascript - 如何通过Enzyme获取依赖组件元素?

javascript - 使用 Jest,获取内部函数

reactjs - enzyme 模拟子组件的onChange事件

unit-testing - Vue-测试工具 | Jest : How to handle dependencies?

reactjs - 类型错误 : Cannot call a class as a function when running Jest test

reactjs - 使用 enzyme 测试重组 - 访问 Prop 问题

javascript - 如何使用 Jest 和 enzyme 为调用另一个函数的函数编写测试?