gpt4 book ai didi

javascript - 如何使用 sinon stub /模拟从 "superclass"复制的依赖项方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:43:43 26 4
gpt4 key购买 nike

我在测试不断变化的 Store 时遇到问题,想要停止调度程序。我已经看到它是如何用 jest 完成的, 但我想用 sinon 达到同样的效果。

这是我的

来源

库/调度程序。完整代码 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;

所以我要 stub 的是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"
});

});

有人可以告诉我如何 stub 吗?

最佳答案

虽然它没有严格回答您的问题,但您可以使用 proxyquire 实现您想要的效果.它允许您在 ItemStore 中对 required 的 AppDispatcher 进行 stub 。例如

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

关于javascript - 如何使用 sinon stub /模拟从 "superclass"复制的依赖项方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26925277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com