Node.js 使用jest测试具有异步函数侦听器的eventEmitter
我定义了一个Node.js 使用jest测试具有异步函数侦听器的eventEmitter,node.js,jestjs,google-cloud-pubsub,eventemitter,Node.js,Jestjs,Google Cloud Pubsub,Eventemitter,我定义了一个async函数,其中包含await语句,并将其用作pubsub订阅消息的侦听器。希望使用jest测试此功能。但面临着一个问题 代码: 测试: 测试失败了 预期已调用模拟函数。 但它没有被调用。 这意味着断言甚至在侦听器函数执行完成之前就完成了。 我如何等待它完成并运行断言。 谢谢你的帮助。 节点v10.11.0,jest“24.8.0”一个简单而简单的解决方案是使用setTimeout进行断言,给异步订阅者足够的时间执行 it("should ack the message", do
async
函数,其中包含await
语句,并将其用作pubsub订阅消息的侦听器。希望使用jest测试此功能。但面临着一个问题
代码:
测试:
测试失败了
预期已调用模拟函数。
但它没有被调用。
这意味着断言甚至在侦听器函数执行完成之前就完成了。
我如何等待它完成并运行断言。
谢谢你的帮助。
节点v10.11.0,jest“24.8.0”一个简单而简单的解决方案是使用
setTimeout
进行断言,给异步订阅者足够的时间执行
it("should ack the message", done => {
pubsubPull();
mockSubscripton.emit("message", message);
setTimeout(() => {
expect(message.ack).toHaveBeenCalled();
done();
}, 100);
});
是的,这是一个解决办法。但只是问我们是否有更好的解决方案来实现这一目标。谢谢@nehero
jest.mock("@google-cloud/pubsub");
jest.mock("./repository");
describe("listener", () => {
const data = {
id: "3ce91594-f648-41bf-9a37-4fa09c4afb3b",
name: "ABCD",
value: 1234
};
const eventBuffer = Buffer.from(JSON.stringify(data));
const message = {
id: "1561624788277",
data: eventBuffer,
ack: jest.fn()
};
const mockSubscripton = new EventEmitter();
const pubsubClient = {
subscription: jest.fn().mockReturnValue(mockSubscripton)
};
beforeAll(() => {
PubSub.mockImplementation(() => pubsubClient);
repository.insert.mockResolvedValue(true);
});
it("should ack the message", (done) => {
pubsubPull();
mockSubscripton.emit("message", message);
expect(message.ack).toHaveBeenCalled();
done();
});
});
it("should ack the message", done => {
pubsubPull();
mockSubscripton.emit("message", message);
setTimeout(() => {
expect(message.ack).toHaveBeenCalled();
done();
}, 100);
});