![](/img/trans.png)
[英]How do I expect a function to be called with specific args with sinon, mocha, and chai in nodejs?
[英]using nodejs, mocha, chai and sinon i would like to stub a function that is called in a route
我有一個非常簡單的應用程序,它是nodejs,express和mysql,我是單元測試的新手,我認為這個應用程序是做得更好的好方法。 我要完成的工作(我認為sinon是答案)是模擬或存根mysql.insertEventIntoDB和rabbit.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();
});
});
感謝您的幫助/指導
請嘗試使用sinon.stub
var stub = sinon.stub(object, "method");
偽造mysql.insertEventIntoDB
var fakeInsertEvt = sinon.stub(mysql, 'insertEventIntoDB');
然后定義該偽函數調用時的行為, 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
循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.