3

我正在尝试使用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();
    })

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

4

1 回答 1

0

这是因为在执行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 });
});
于 2021-12-09T20:42:40.350 回答