繁体   English   中英

使用 jest 和 axios 模拟 api 调用失败一定次数

[英]Mock api call to fail a certain number of times with jest and 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
  };
});

但是我怎样才能使 post 调用失败,例如 3 次然后成功?

知道了:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM