Ouwen Huang
Ouwen Huang

Reputation: 1097

Mocha Testing a post function

Hmmm just double checking if I'm making some silly error, however doesn't seem like it. I just want this test to pass but it keeps giving me a timeout error. This module should work, it is sending mail correctly, but mocha keeps giving a timeout.

// describe('POST /api/mail', function() {
//  it('should successfully send mail', function(done) {
//      request(app)
//          .post('/api/mail')
//          .send(form)
//          .expect(200)
//          .end(function(err, res) {
//              if (err) return done(err);
//              done();
//          });
//  });
// });

This is the actual function being tested

'use strict';
var transporter = require('./transporter.js').transporter;

exports.sendMail = function(req, res){
    // setup e-mail data with unicode symbols
    var mailOptions = {
        from: req.body.name + ' <'+req.body.email+'>',
        to: '[email protected]',
        subject: req.body.subject,
        text: req.body.message
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, function(err, info){
        if(err){
            res.status(400); //error
        }else{
            res.status(200); //success
        }
    });
};

Upvotes: 0

Views: 732

Answers (1)

Juanjo Espa&#241;a
Juanjo Espa&#241;a

Reputation: 46

I think Mocha is waiting for sendMail result via callback. I have a similar sendMail, using nodemailer.js, in an application:

    function send(fr, to, sj, msg, callback){

    //...

    var transport = nodemailer.createTransport();

    console.log("Message content: "+msg);

    transport.sendMail({from:fr, to:to, subject: sj, text: "\r\n\r\n" + msg},
        function(err,response){
            if(err){
                callback(err);          
            }else{          
                callback(response);
            }
        });
};

In my test:

describe('when this example is tested',function(done){
it('should be sending an email', function(done){            
    mailSender.sendMail('[email protected]', 'Test', 'Test text', function(sent){            
        sent.should.be.ok;  
        done();
    });     
});

You get the sent in your callback and then Mocha can reach the done() method to indicate the test has finished.

Also, you can use Supertest to test your endpoint. It should be something like this:

it('should return 200 on /api/mail', function(done) {

    supertest('http://localhost:3000').post('/api/mail').expect(200)
    .end(
        function(err, res) {
            if (err) {
                return done(err);
            }
            done();
        });
});

Upvotes: 1

Related Questions