mercredi 27 juillet 2016

How can I test this Node.js module?

I have the following Node module which I would like to test:

'use strict';

var queueClientService = require('shared-services/lib/queueClient');
var Result = require('shared-services/lib/models/result');

module.exports.start = function() {
    var exchangeName = 'retuls';
    var exchangeType = 'fanout';
    var queueName = 'result.database';
    var options = {};

    queueClientService.consume(exchangeName, exchangeType, queueName, options, function(channel, message) {
        try {
            var data = JSON.parse(message.content.toString());
        }
        catch (error) {
            // Unparsable data; acknowledge the message and skip.
            return channel.ack(message);
        }

        if (data._id) {
            // If the incoming data an _id value, then it is already
            // saved to the database, so ignore it.
            return channel.ack(message);
        }

        // Use the data model directly to create the document.
        Result.create(data, function(error) {
            // Acknowledge the message.
            channel.ack(message);
        });
    });
};

With this module, when the start() method is called, it connects to a RabbitMQ service (via queueClientService) and listens on a channel for incoming messages. the last parameter to queueClientService.consume() is a callback to be called when a new message arrives in the queue. I would like to test that this callback does what I expect (i.e., Creates a "result" document).

What things will I need to do in order to successfully test this module? Here are some ideas I have so far:

  1. Mock queueClientService.
  2. Mock Result (which is a Mongoose data model).
  3. Somehow make require('shared-services/lib/queueClient') return the queueClientService mock.
  4. Somehow make require('shared-services/lib/models/result') return the Result mock.
  5. Load the module and call start().
  6. expect() that Result attempts creation of a MongoDB document OR expect() that Result.create() is .calledOnce.

Aucun commentaire:

Enregistrer un commentaire