gpt4 book ai didi

node.js - 使用 amqplib-mocks 库进行 rabbitMQ 单元测试

转载 作者:行者123 更新时间:2023-12-05 07:22:23 25 4
gpt4 key购买 nike

我正在尝试使用 amqplib-mocks 编写单元测试但我无法使用来自消费者的消息,我变得不确定,我尝试调试但没有成功。

describe("Rabbitmq testing Server", () => {
let connection, channel;

before(async () => {
connection = await amqplib.connect("amqp://localhost");
channel = await connection.createChannel();

await channel.assertExchange(messagesExchange, exchangeType);

isCreated = await channel.assertQueue(queue);
isCreated.queue ? console.log('queue created') : 'Queue not created or already exist';

await channel.bindQueue(queue, messagesExchange, routingKey);

const isPublish = channel.publish(messagesExchange, routingKey, Buffer.from('should pass test')).valueOf();
isPublish ? console.log('message published successfully') : 'message not published';
});

it("should create the channel", () => {
assert.isObject(channel);
});

it("should register the method call", () => {
expect(connection.createChannel()).to.have.been.all.keys;
expect(connection.createChannel()).to.have.been.all.members;
});

it("should consumer consume message from queue", async () => {
let result: string;
const consumer = await channel.consume(queue, (msg) => {
result = msg.content.toString();
console.log(result);
}, { noAck: true });

// expect(result).to.be.equal(JSON.stringify({ success: true }));
});

after(() => {
amqplib.reset();
})

前两个测试通过,但第三个测试得到未定义的值。任何帮助将不胜感激。

最佳答案

这是因为 result 在执行 expect 之前没有返回。

上面代码中发生的事情是

  1. 正在执行channel.consume
  2. 正在执行expect语句
  3. 正在执行回调 - msg.content.toString()
  4. 正在执行 console.log(result)

您可以尝试将 expect 放入回调中并使用 done在测试完成时声明:

it("should consumer consume message from queue", async (done) => {
let result: string;
const consumer = await channel.consume(queue, (msg) => {
result = msg.content.toString();
console.log(result);
expect(result).to.be.equal(JSON.stringify({ success: true }));
done();
}, { noAck: true });
});

关于node.js - 使用 amqplib-mocks 库进行 rabbitMQ 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56544583/

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