如何使用 sinon.js 存根链接函数

How to stub chained functions using sinon.js

为了编写我的测试,我在堆栈中使用了 mocha 框架,Chai as an assertion library and 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),
    };

不会return对象,并导致错误:

TypeError: Cannot call method 'on' of undefined

请告诉我,我如何存根链接函数?

第一种方法对你的请求对象存根是正确的,但是,如果你想测试是否调用了这些方法and/or检查调用它们时使用了哪些参数,也许你会更容易而是使用间谍。下面是关于如何使用它们的 sinon-chai documentation

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

});