如何使用sinon存储/模拟从“超类”复制的依赖项方法

时间:2014-11-14 07:48:45

标签: javascript browserify sinon reactjs-flux

我在测试商店时遇到了问题,希望将调度程序排除在外。我已经看到它是如何用jest完成的,但我希望与sinon达到同样的效果。

这就是我所拥有的

来源

LIB /调度程序。完整代码here

var invariant = require('./invariant');

//...

function Dispatcher() {
  this.$Dispatcher_callbacks = {};
}

Dispatcher.prototype.register=function(callback) {
  var id = _prefix + _lastID++;
  this.$Dispatcher_callbacks[id] = callback;
  return id;
};


// ...

module.exports = Dispatcher;

分派器

module.exports.Dispatcher = require('./lib/Dispatcher')

AppDispatcher

var Dispatcher = require('flux').Dispatcher;
var copyProperties = require('react/lib/copyProperties');
var AppDispatcher = copyProperties(new Dispatcher(), {

  handleViewAction: function(action) {
    this.dispatch({
      source: 'VIEW_ACTION',
      action: action
    });
  }

});

module.exports = AppDispatcher;

ItemStore 我要测试的人

var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var ItemConstants = require('../constants/ItemConstants');
var merge = require('react/lib/merge');

var CHANGE_EVENT = 'change';

var _items = [];

var ItemStore = merge(EventEmitter.prototype, {

  getSoekeresultat: function() {
    return _items;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  }
});

AppDispatcher.register(function(payload) {
  var action = payload.action;

  switch(action.actionType) {
    case ItemConstants.ITEMS_FETCHED:
      _items = action.payload;
      ItemStore.emitChange();
      break;
    default:
  }

  return true; // No errors.  Needed by promise in Dispatcher.
});

module.exports = ItemStore;

所以我想要的存根是AppDispatcher.register。我该怎么做?

我尝试过几种方式,最后一次尝试就是这样:

var sinon = require("sinon");
require("jasmine-sinon");

describe("ItemStore", function(){
  var AppDispatcher = require('js/dispatcher/AppDispatcher.js');
  sinon.stub(AppDispatcher, 'register', function () {
    console.log("stub");
  });
  it("should use stub when called directly", function(){
    AppDispatcher.register(function (payload) {
    });
    //outputs "stub"
  });
  it("should use stub when requiring itemstore", function(){
    var ItemStore = require('js/stores/ItemStore.js');
  // doesn't output "stub"
  });

});

有人可以告诉我如何存根吗?

1 个答案:

答案 0 :(得分:0)

虽然它没有严格回答您的问题,但您可以实现您尝试使用proxyquire的功能。它允许您在AppDispatcher内隐藏require ItemStore。 e.g。

var proxyquire = require('proxyquire');
var AppDispatcher = require('js/dispatcher/AppDispatcher.js');
var StubbedAppDispatcher = sinon.stub(AppDispatcher)

/*
 * This will load the `ItemStore` module, satisfying it's `AppDispatcher`
 * dependency (the `require('../dispatcher/AppDispatcher')` statement)
 * with our stubbed version.
 */
var ItemStore = proxyquire('js/stores/ItemStore.js', {
  '../dispatcher/AppDispatcher': StubbedAppDispatcher
});