简体   繁体   English

摩卡测试后功能

[英]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. 该模块应该可以正常工作,可以正确发送邮件,但是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();
//          });
//  });
// });

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

I think Mocha is waiting for sendMail result via callback. 我认为Mocha正在等待通过回调的sendMail结果。 I have a similar sendMail, using nodemailer.js, in an application: 我在应用程序中使用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);
            }
        });
};

In my test: 在我的测试中:

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

You get the sent in your callback and then Mocha can reach the done() method to indicate the test has finished. 您在回调中收到发送的内容,然后Mocha可以到达done()方法以指示测试已完成。

Also, you can use Supertest to test your endpoint. 另外,您可以使用Supertest来测试您的端点。 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();
        });
});

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

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