SinonJS为内部对象函数调用了一次或callCount问题

时间:2017-08-28 19:39:25

标签: javascript unit-testing testing sinon

使用SinonJS 3运行测试我面临以下问题

测试有什么问题?

console.log(spyRequester.callCount);

var message = 'Welcome to the AWS Podcast. You can say, play the audio to begin the podcast.'; var reprompt = 'You can say, play the audio, to begin.'; 行 应该打印1但它打印0

https://codepen.io/thiagoh/pen/XaxBjr?editors=1011

1 个答案:

答案 0 :(得分:1)

您当前的createIfNotExists实施正在调用其范围内捕获的_doCreate。如果你想让它运行你的模拟,你应该以某种方式使这些函数之间的“链接”动态。在您的特定情况下,使用this._doCreate应该有效。但如果使用不正确的上下文调用,它会使createIfNotExists失败。

var creator = (function() {

  var createIfNotExists = function createIfNotExists() {
    // pick _doCreate from the context or use default.
    (this._doCreate || _doCreate)();
  };

  var _doCreate = function _doCreate() {
    console.log('_doCreate was called');
  };

  return {
    createIfNotExists:createIfNotExists,
    _doCreate:_doCreate
  };
}());

var util = {
  createIfNotExists:creator.createIfNotExists,
  _doCreate:creator._doCreate
};

var spyRequester = sinon.spy(util, '_doCreate');
util.createIfNotExists();

console.log(spyRequester.callCount); // prints 1
<script src="https://unpkg.com/sinon@3.2.1/pkg/sinon-3.2.1.js"></script>