简体   繁体   中英

Stubbing async.waterfall with Sinon.JS

I am trying to test async.waterfall by stubbing one of my functions using Sinon.js .

// functions.js
module.exports = {
  // function I don't want to run
  doBigThing: function() {
    console.log("[doBigThing] was called");
  },

  // function I want to stub
  myFunction: function(number, callback) {
    console.log("[myFunction] was called");
    doBigThing();
    callback(null, number);
  },

  // function I want to test
  waterfall: function(callback) {
    return async.waterfall([
      async.constant(5), // 5 just for the demo
      myFunction
    ], callback);
  }
}

And my test is:

describe('water', function() {
  it ('successfully falls', function() {
    // function under test
    var waterfall = functions.waterfall;

    var callback = function(err, number) {
      expect(err).to.be.null;
      expect(number).to.equal(5);
    };

    // I would like this stub to run instead of functions.myFunction
    sinon.stub(functions, 'myFunction', function(number, callback) {
      console.log("[myFunction] stub was called");
      callback(null, number);
    });

    waterfall(callback);
    // I suppose this is happening: myFunction(5, callback) 
    expect(functions.myFunction.withArgs(5, callback)).to.have.been.called;
    expect(callback).to.have.been.called;
  });
});

So the test passes, but the stub is ignored, because doBigThing was called:

  Water
    ✓ successfully falls
[myFunction] was called
[doBigThing] was called

Instead I would like to see

  Water
    ✓ successfully falls
[myFunction] stub was called

I am probably missing out on something and I would appreciate your help.

You're stubbing functions object's method myFunction , but in waterfall method you're calling a myFunction function (I actually can't run your code in my environment, I get "ReferenceError: myFunction is not defined"). So this should work:

// functions.js
var functions = {
  // function I don't want to run
  doBigThing: function() {
    console.log("[doBigThing] was called");
  },

  // function I want to stub
  myFunction: function(number, callback) {
    console.log("[myFunction] was called");
    functions.doBigThing(); // CHANGE HERE
    callback(null, number);
  },

  // function I want to test
  waterfall: function(callback) {
    return async.waterfall([
      async.constant(5), // 5 just for the demo
      functions.myFunction // CHANGE HERE
    ], callback);
  }
};

module.exports = functions;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM