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

时间:2019-06-06 07:10:51

标签: 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);
  });
});

1 个答案:

答案 0 :(得分:0)

奋斗了几个小时。我找到了原因。造成此问题的原因是Bad Request: JSON parse error: Expected array or string.; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string. at [Source: (PushbackInputStream); line: 1, column: 159] (through reference chain: com.xxx.MyObj["someDate"])

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