【问题标题】:How to stub chained functions using sinon.js如何使用 sinon.js 存根链式函数
【发布时间】:2015-10-26 20:40:01
【问题描述】:

为了编写我的测试,我在堆栈中使用 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');

stub的returns()方法的使用:

requestStub = {
        get: sinon.stub().returns(this),
        on:  sinon.stub().returns(this),
    };

不会返回对象,并导致错误:

TypeError: 无法调用未定义的“on”方法

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

【问题讨论】:

    标签: javascript node.js unit-testing mocha.js sinon


    【解决方案1】:

    第一种方法对于存根请求对象是正确的,但是,如果您想测试方法是否被调用和/或检查调用它们时使用了哪些参数,那么使用间谍可能会更容易。这是sinon-chai documentation 的使用方法

    【讨论】:

      【解决方案2】:
      '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;
          });
        });
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-06
        • 2016-12-02
        • 2017-07-12
        • 2012-01-09
        • 1970-01-01
        • 2020-07-01
        • 2016-08-16
        • 1970-01-01
        相关资源
        最近更新 更多