摩卡测试帖子功能

时间:2014-10-13 06:08:55

标签: javascript node.js testing mocha

嗯,只是仔细检查我是否犯了一些愚蠢的错误,但是看起来并不像。我只是希望这个测试通过,但它一直给我一个超时错误。这个模块应该可以工作,它正确地发送邮件,但是mocha不断给出超时。

// 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();
//          });
//  });
// });

这是正在测试的实际功能

'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: 'test@gmail.com',
        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
        }
    });
};

1 个答案:

答案 0 :(得分:1)

我认为Mocha正在通过回调等待sendMail结果。我在应用程序中使用nodemailer.js有一个类似的sendMail:

    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);
            }
        });
};

在我的测试中:

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

你在回调中得到了发送,然后Mocha可以到达done()方法来表明测试已经完成。

此外,您可以使用Supertest来测试您的终端。它应该是这样的:

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();
        });
});