Reputation: 340
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
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
Reputation: 7092
You can try one of the following:
you can create a valid rabbit-mq connection using a docker iamage docker-rabbitmq and make real requests to your application but this is not unit testing, but more like integration testing.
You can mock it using sinon a very good article I can suggest on this topic is Best practices for spies, stubs, and mocks in sinonjs
Upvotes: 5