我写了一个测试,总是失败,在异步节流上;方法(该方法将接受另一个异步方法作为参数,并且只要它抛出异常就执行该方法,或者在达到允许的最大重试次数时停止)。我希望这个测试大多数时候都能成功。
我让这个节流方法在一个独立的脚本中按预期工作。
但是当涉及到在测试(jest)中执行相同的代码时,似乎没有等待对throttle()的调用,并且我无法理解测试输出来自何处(jest接收的输出:{}).
当我运行测试时,我可以将funcThatMayProcessOrThrowError
的假执行时间更改为例如10s,这不会对测试执行时间产生影响,测试执行时间始终在1.2s左右。
Jest正在使用选项--verbose=false --silent=false
运行,但我没有在控制台上看到任何日志(我希望经常看到...Error during the call... retrying in...
)。
我错过了什么让这个测试按预期执行
?lib.js
const throttle = async (method, intervals, index = null) => {
const execResult = await method()
.catch(async error => {
// 1. determinate the interval to apply
if (index === null) index = 0;
// 2. Limit throttling has been reached ?
if (index === intervals.length) {
throw error;
}
console.log(`[#${index}] Error during the call... retrying in ${intervals[index]}ms. (Error: ${error.message})`);
await sleep(intervals[index]);
return await throttle(method, intervals, index + 1);
});
return execResult;
};
const sleep = (milliseconds) => {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
};
const funcThatMayProcessOrThrowError = async (anyStringValue) => {
await sleep(125);//simulate an execution time (ms)
console.log("Start processing of:", anyStringValue);
//randomly raise an error
const nb = Math.random();
//console.log(`Random number: ${nb}`);
if(nb > .11) {
//chances are about 1 in 10 to execute the function without throwing an error
throw new Error(`An error was thrown during processing of ${anyStringValue} (nb: ${nb})`);
}
return `${anyStringValue} processed`;
};
const run = async () => {
var intervals = [ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100, 100 ]; //milliseconds
const stringToProcess = "chandelier";
const result = await throttle(async () => await funcThatMayProcessOrThrowError(stringToProcess), intervals)
.catch(error => console.log("Error",error.message));
console.log("--> Great !", result);
};
//launch it (works perfectly as expected)
(async () => {
console.log("starting");
await run();
console.log("finishing");
})();
. js
describe("throttle()", () => {
it("should repeat execution of a function until a success, and before reaching the max number of retries", async() => {
const stringToProcess = "chandelier";
await expect(lib.run(stringToProcess)).toEqual(`${stringToProcess} processed`);
});
});
/*
Test output:
expect(received).toEqual(expected) // deep equality
Expected: "chandelier processed"
Received: {}
*/
好吧,我写这个问题花的时间比回答它花的时间还多。
测试缺少.resolves
,这是解析调用
it("should repeat execution of a function until a success, and before reaching the max number of retries", async() => {
const stringToProcess = "chandelier";
await expect(lib.run(stringToProcess)).resolves.toEqual(`${stringToProcess} processed`);
});
现在,测试成功了,并显示了我所期望的日志。