3

I am trying to write unit tests with amqplib-mocks but i can not consume message from consumer, i am getting undefined and i try to debug but not successfull.

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();
    })

first two tests are passing but third test getting undefined value. Any help would be appreciate.

U rock
  • 717
  • 2
  • 13
  • 32

1 Answers1

0

This is because the result is not being returned before the expect is executed.

What's happening in your code above is

  1. the channel.consume is being executed
  2. the expect statement is being executed
  3. the callback is being executed - msg.content.toString()
  4. the console.log(result) is being executed.

What you could try is putting the expect inside your callback and using done to declare when your test has completed:

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 });
});
richardw
  • 196
  • 1
  • 5