我在测试流通中的商店时遇到问题,想要存根调度程序。我已经看过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"
  });

});

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

最佳答案

尽管并不能严格回答您的问题,但是您可以使用proxyquire实现您想要的目标。它允许您将AppDispatcher内的require d的ItemStore存根。例如

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

09-27 04:34