模拟API调用使用Jest和Axios失败一定次数

时间:2020-01-23 16:14:01

标签: javascript api mocking jestjs axios

我有一个函数,该函数设置一个api调用,然后将该函数传递给重试函数,该函数执行该调用并在失败时重试该调用,最多5次。

public someAPICall() {
        const promiseFunction = () => axios.post('/some/path/', {
            headers: {
                //some headers in here
            },
        });
        return executePromise(promiseFunction, 5);
}

private async executePromise(promiseFunction, numberOfTimesToTryAgain) {
    try {
        // execute api call
        return await promiseFunction();
    }
    catch (error) {
        if (retries > 0) {
            // try api call again if it has failed less than 5 times
            return executePromise(promiseFunction, --numberOfTimesToTryAgain);
        }
        return error;
    }
}

我想测试someAPICall并使用jest模拟axios调用的结果以使一定次数失败。 我可以在测试文件中模拟axios.post调用:

jest.mock('axios');
mockPost = jest.fn(() => {});
(<jest.Mock>axios.create) = jest.fn(() => {
  return {
    post: mockPost
  };
});

但是我该怎么做,以便邮寄呼叫失败(例如3次,然后又成功)?

1 个答案:

答案 0 :(得分:0)

知道了:

 mockPostFailTwice = jest.fn()
.mockImplementation(() => {
  return 200;
})
.mockImplementationOnce(() => {
  throw 500;
})
.mockImplementationOnce(() => {
  throw 500;
});

这会导致后期执行在前2次抛出500错误,并在第3次返回200错误。