vendredi 24 avril 2015

Nodejs app - testing `fs`, `request` and `nodemailer`

I need to test the following code, which will be run on amazon's AWS Lambda. However I am relatively new to unit testing nodejs, and am having some trouble with the logic I need to apply to test the code.

For the request to the api, I was thinking of using nock to mock the api and for the fs module, use mock-fs. For nodemailer would using a stub be a good approach?

Is it ok to have two mocks in my test?

Would I need proxyquire to require fs and nodemailer?

This is the code I am trying to test:

'use strict'

var fs = require('fs');
var _ = require('underscore');
var request = require("request");
var nodemailer = require("nodemailer");


exports.invoicer = function (context, url) {

    // set-up our transporter object with credentials
    var transporter = nodemailer.createTransport({
        service: "someEmailService.com",
        auth: {
            user: 'MyUsername',
            password: 'MyPassword',
            port: 887,
            encryption: 'tls'
        }
    });

    fs.readFile('./index.html', function(err, data){

        if (err) {
            context.done(new Error("There was an error reading the file ---> %s", error.message));
        }

        data = data.toString();

        var template = _.template(data);

        // request should return a
        request(url, function (error, response, body) {
            if(error) {
                context.done(new Error("There was an error with request --> %s", error.message));
            }
            if (!error && response.statusCode == 200) {
                console.log(body);
                var populated_html = template(body); // not sure about this!!
                console.log(populated_html);

                var mailOptions = {
                    from: '<meToYou@gmail.com>', // sender address
                    to: '<youToMe@gmail.com>', // recipient
                    subject: 'Invoice',
                    html: populated_html
                }

                transporter.sendMail(mailOptions, function(error, info){
                    if(error){
                        console.log(error);
                    }else{
                        console.log('Message sent: ' + info.response);
                        context.done();
                    }
                });
            }
        });
    });
};

Aucun commentaire:

Enregistrer un commentaire