Mocha正在测试一个post函数

Mocha Testing a post function

本文关键字:一个 post 函数 测试 Mocha      更新时间:2023-09-26

嗯,我只是反复检查我是否犯了一些愚蠢的错误,但看起来并不是。我只想通过这个测试,但它一直给我一个超时错误。这个模块应该可以工作,它正确地发送邮件,但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结果。我在一个应用程序中有一个类似的sendMail,使用nodemailer.js:

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

您在回调中收到send,然后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();
        });
});