繁体   English   中英

摩卡测试后功能

[英]Mocha Testing a post function

嗯,只是仔细检查我是否犯了一些愚蠢的错误,但是似乎不是这样。 我只希望该测试通过,但它一直给我超时错误。 该模块应该可以正常工作,可以正确发送邮件,但是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
        }
    });
};

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM