Amir
Amir

Reputation: 340

How to check rabbit connection in node js for unit test using mocha and chi

I'm using amqplib-package for connecting to RabbitMQ in nodeJS and want to know how I can check/verify my RabbitMQ-connection using Mocha and Chai in nodeJS?

Upvotes: 3

Views: 4083

Answers (2)

Yugank Sharma
Yugank Sharma

Reputation: 1

If you are using ampqlib package and you want to test whether the connection is established or not then it is not considered as a unit test, we can call it an integration test.

Other answers have good content about integration testing, but for unit testing you can use amqplib-mocks (https://www.npmjs.com/package/amqplib-mocks) which is a simple mocking framework for amqplib.

For a basic unit test you can check if amqp.connect(url) is called and expect the URL you want.

I can also show a basic example how you can get a stubbed connection object: (ps: This is not a running code, this is just for reference)

subscriber.js

const amqp = require('amqplib');
class Subscriber {
   async getConnection(url) {
        const connection = await amqp.connect(url);
        return connection;
   }
}

Subscriber class has a method getConnection which establishes and return a connection object with rabbitmq.

subscriber.test.js

const amqpMock = require('amqplib-mocks');
const sinon = require('sinon');

const mockConnection = await amqpMock.connect('mockurl.com');
const getConnectionStub = sinon.stub(Subscriber.prototype, 'getConnection').returns(mockConnection);

In above code you can either stub ampq.connect directly or stub getConnection method and return a connection object as returned by amqp-mock's connect method.

To know more about sinon used above, click.

Upvotes: 0

Alexandru Olaru
Alexandru Olaru

Reputation: 7092

You can try one of the following:

Upvotes: 5

Related Questions