【问题标题】:using nodejs, mocha, chai and sinon i would like to stub a function that is called in a route使用 nodejs、mocha、chai 和 sinon 我想存根一个在路由中调用的函数
【发布时间】:2016-03-08 23:53:33
【问题描述】:

我有一个非常简单的应用程序,它是 nodejs、express 和 mysql 我是单元测试的新手,我认为这个应用程序是做得更好的好方法。 我想要完成的(我认为 sinon 是答案)是模拟或存根 mysql.insertEventIntoDBrabbit.addToRabbitMQ

在我的应用中我有

app.use('/sendgrid', sendgrid(pool, config, logger) );

在我的 sendgrid.js 中有

var express = require('express');
var mysql = require('../app/utils/mysql');
var rabbit = require('../app/utils/rabbitMQ');

module.exports = function (dbpool, config, logger) {
  var router = express.Router();

  router.post('/callback', function (req, res) {
    for (var x=0 ; x < req.body.length ; x++ ){
       mysql.insertEventIntoDB(dbpool, req.body[x], logger);
       rabbit.addToRabbitMQ(config,req.body[x], logger)
    }
    res.json({ status: 'OK' });
  });

  return router;
}

我已经看过很多存根和间谍的例子,但只是无法从这些测试中弄清楚如何做到这一点。这是我的一个测试示例

it('should get an OK for delivered POST', function(done) {
 chai.request(server)
  .post('/sendgrid/callback')
  .send(delivered)
  .end(function(err, res){
    res.should.have.status(200);
    res.should.be.json;
    res.body.should.be.a('object');
    res.body.should.have.property('status');
    res.body.status.should.equal('OK');
    done();
  });
 });

感谢任何帮助/指导

【问题讨论】:

    标签: node.js mocha.js sinon chai


    【解决方案1】:

    请尝试使用sinon.stub

    var stub = sinon.stub(object, "method");
    

    伪造mysql.insertEventIntoDB

    var fakeInsertEvt = sinon.stub(mysql, 'insertEventIntoDB');
    

    然后定义这个fake函数被调用时的行为,onCall的参数就是这个函数被调用的次数。

    fakeInsertEvt.onCall(0).return(0);
    

    或者按照var stub = sinon.stub(object, "method", func);,用一个回调函数来伪造上面的函数

    var fakeInsertEvt = sinon.stub(mysql, 'insertEventIntoDB', function(){
                                              return Math.random();
                                        });
    

    在您的情况下,似乎第二个选项可能更好,因为mysql.insertEventIntoDB 中有for 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 2020-08-20
      • 2017-10-08
      • 2016-09-25
      • 1970-01-01
      相关资源
      最近更新 更多