Promise.resolve 从笑话模拟函数返回未定义

Car*_*los 2 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");
    }
  };
Run Code Online (Sandbox Code Playgroud)

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

Car*_*los 6

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

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