gpt4 book ai didi

typescript - Jest : Test recursive call inside Promise

转载 作者:搜寻专家 更新时间:2023-10-30 21:36:04 28 4
gpt4 key购买 nike

我在测试以下类(class)时遇到了一些问题。

interface Connector {
connect: () => Promise<void>;
}

class Unit {
private connector: Connector;

constructor(connector: Connector) {
this.connector = connector;
}

public attemptConnect(iteration: number, max: number): void {
console.log("attempt" + iteration);

this.connector.connect()
.then(() => {
console.log("connected");
})
.catch((error) => {
if (iteration < max) {
this.attemptConnect(iteration + 1, max);
}
});
}
}

我想测试 Connector.connect() 函数被调用的次数是否正确。我正在尝试通过以下方式开 Jest :

describe("Unit", () => {
it("fails to record more than one recursion", async () => {
const connector: Connector = {
connect: jest.fn().mockRejectedValue(new Error("foo")),
};
const unit: Unit = new Unit(connector);

await unit.attemptConnect(1, 4);

expect((connector.connect as jest.Mock).mock.calls.length).toBe(4);
});
});

不幸的是 expect() 调用失败,说

Error: expect(received).toBe(expected) // Object.is equality

Expected: 4
Received: 1

如果我使用调试器并观察的值

(connector.connect as jest.Mock).mock.calls.length

我可以看到通话记录正确。只有当测试完成时,数字才错误。

感谢您的帮助!

最佳答案

解决方案一

attemptConnect() 中返回 promise :

public attemptConnect(iteration: number, max: number): Promise<void> {
console.log("attempt" + iteration);

return this.connector.connect()
.then(() => {
console.log("connected");
})
.catch((error) => {
if (iteration < max) {
return this.attemptConnect(iteration + 1, max);
}
});
}

方案二

await 测试中所需的事件循环周期数:

describe("Unit", () => {
it("fails to record more than one recursion", async () => {
const connector: Connector = {
connect: jest.fn().mockRejectedValue(new Error("foo")),
};
const unit: Unit = new Unit(connector);

unit.attemptConnect(1, 4);

// await enough event loop cycles for all the callbacks queued
// by then() and catch() to run, in this case 5:
await Promise.resolve().then().then().then().then();

expect((connector.connect as jest.Mock).mock.calls.length).toBe(4);
});
});

详情

测试等待attemptConnect(),但由于它没有返回任何东西,所以没有什么可以await,同步测试继续执行。在 then()catch() 排队的回调有机会运行之前,expect() 运行并失败。

关于typescript - Jest : Test recursive call inside Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51916354/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com