为了编写我的测试,我在堆栈中使用mocha框架,Chai作为断言库,Sinon.JS用于模拟,存根和间谍。假设我有一些链式函数,例如:
request
.get(url)
.on('error', (error) => {
console.log(error);
})
.on('response', (res) => {
console.log(res);
})
.pipe(fs.createWriteStream('log.txt'));
考虑到我想用必要的参数断言他们的调用,最好的方法是什么?
这样的结构:
requestStub = {
get: function() {
return this;
},
on: function() {
return this;
}
//...
};
不允许我断言这些方法:
expect(requestStub.get).to.be.called;
expect(requestStub.on).to.be.calledWith('a', 'b');
存根的returns()
方法的用法:
requestStub = {
get: sinon.stub().returns(this),
on: sinon.stub().returns(this),
};
不会返回该对象,并导致错误:
TypeError:无法调用未定义的方法'on'
请告诉我,我怎样才能存根链接函数?
答案 0 :(得分:1)
第一种方法对于存根请求对象是正确的,但是,如果你想测试方法是否被调用和/或检查调用它们时使用了哪些参数,也许你会更容易使用间谍代替。这是关于如何使用它们的sinon-chai documentation
答案 1 :(得分:1)
'use strict';
var proxyquire = require('proxyquire').noPreserveCache();
var chai = require('chai');
// Load Chai assertions
var expect = chai.expect;
var assert = chai.assert;
chai.should();
var sinon = require('sinon');
chai.use(require('sinon-chai'));
var routerStub = {
get: function() {
return this;
},
on: function() {
return this;
}
}
var routerGetSpy;
var configStub={
API:"http://test:9000"
}
var helperStub={
}
var reqStub = {
url:"/languages",
pipe: function(){
return resStub
}
}
var resStub={
pipe: sinon.spy()
}
// require the index with our stubbed out modules
var Service = proxyquire('../../../src/gamehub/index', {
'request': routerStub,
'../config': configStub,
'../utils/helper': helperStub
});
describe('XXXX Servie API Router:', function() {
describe('GET /api/yy/* will make request to yy service defined in config as "<service host>/api/* "' , function() {
it('should verify that posts routes to post.controller.allPosts', function() {
var get = sinon.spy(routerStub, 'get')
Service(reqStub);
expect(get.withArgs("http://test:9000/api/languages")).to.have.been.calledOnce;
});
});
});