开玩笑的嘲笑承诺方法调用了错误的次数

Ton*_*ang 5 javascript rest promise typescript jestjs

作为我的 redux 操作的一部分,它发出了几个连续的 api 请求。该apiCall方法返回一个带有某个值的 Promise,并且该值被后续apiCall用于发出另一个请求,依此类推。我正在使用 Jest 来测试这些 api 调用。

const myAPI = {
  apiCall(param: any): Promise<any> {
    return new Promise((resolve, reject) => {
      resolve('result');
    });
  },
};

const serialAPIRequests = () => {
  myAPI.apiCall('first_param')
    .then((result) => {
      console.log(result);
      return myAPI.apiCall(result);
    })
    .then((result) => {
      console.log(result);
      return myAPI.apiCall(result);
    })
    .then((result) => {
      console.log(result);
      return Promise.resolve(result);
    });
};
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个测试,以确保apiCall被调用的次数正确且参数正确。

describe.only('my test', () => {
  it('should test api stuff', () => {
    myAPI.apiCall = jest.fn()
      .mockReturnValueOnce(Promise.resolve('result1'))
      .mockReturnValueOnce(Promise.resolve('result2'))
      .mockReturnValueOnce(Promise.resolve('result3'));
    serialAPIRequests();
    expect(myAPI.apiCall).toHaveBeenCalledTimes(3);
  });
});
Run Code Online (Sandbox Code Playgroud)

发生的事情是 Jest 报告 Expected mock function to have been called three times, but it was called one time.

Jest 测试结果表明

  ? Console

console.log 
  result1
console.log 
  result2
console.log 
  result3

 ? my test › should test api stuff

expect(jest.fn()).toHaveBeenCalledTimes(3)

Expected mock function to have been called three times, but it was called one time.
Run Code Online (Sandbox Code Playgroud)

console.log 显示不同值的事实意味着模拟返回正确地通过模拟函数并被调用了 3 次。

什么可能导致这种情况以及如何正确测试此功能?

lta*_*ajs 7

使用 async/await 测试异步代码。在此处阅读更多信息:https : //facebook.github.io/jest/docs/en/tutorial-async.html

describe.only('my test', () => {
      it('should test api stuff', async () => {
        myAPI.apiCall = jest.fn()
          .mockReturnValueOnce(Promise.resolve('result1'))
          .mockReturnValueOnce(Promise.resolve('result2'))
          .mockReturnValueOnce(Promise.resolve('result3'));
        await serialAPIRequests();
        expect(myAPI.apiCall).toHaveBeenCalledTimes(3);
      });
    });
Run Code Online (Sandbox Code Playgroud)