forked from goldbergyoni/nodejs-testing-best-practices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfake-message-queue-provider.js
58 lines (48 loc) · 1.85 KB
/
fake-message-queue-provider.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const { EventEmitter } = require('events');
// This class is the heart of the MQ testing - It replaces the MQ provider client library
// and implement the same signature, but each method does nothing but emit an event which the test
// can verify that indeed happened
class FakeMessageQueueProvider extends EventEmitter {
async nack() {
const eventDescription = { event: 'message-rejected' };
this.emit('message-rejected', eventDescription); // Multiple events allows the test to filter for the relevant event
this.emit('message-handled', eventDescription);
}
async ack() {
const eventDescription = { event: 'message-acknowledged' };
this.emit('message-acknowledged', eventDescription);
this.emit('message-handled', eventDescription);
}
async sendToQueue(queueName, message) {
this.emit('message-sent', message);
}
async publish(exchangeName, routingKey, message) {
this.emit('message-published', message);
this.pushMessageToQueue('unknown', message);
}
async assertQueue() {}
async consume(queueName, messageHandler) {
// We just save the callback (handler) locally, whenever a message will put into this queue
// we will fire this handler
this.messageHandler = messageHandler;
}
// This is the only method that does not exist in the MQ client library
// It allows us to fake like there is a new message in the queue and start a flow
async pushMessageToQueue(queue, newMessage) {
if (this.messageHandler) {
this.messageHandler({content: newMessage})
} else {
// Just warning and no exception because the test might want to simulate that
console.error(
'A new message put into the fake queue but no handlers exist'
);
}
}
async createChannel() {
return this;
}
async connect() {
return this;
}
}
module.exports = { FakeMessageQueueProvider };