我正在寻找,如何模拟由 ember 的 ioc 容器注入的属性。目标是对一个类进行单元测试。例如,我想测试一个具有许多注入属性的控制器,我可以在它的容器中注入一些“controller:NAME”来模拟所需的控制器,但是如何模拟其余的?请参阅上面的代码了解:
//=====================================
// Source :
//=====================================
App = Ember.Application.create();
App.ApplicationController = Ember.Controller.extend({
});
App.IndexController = Ember.Controller.extend({
needs:["application"]
});
App.Session = Em.Object.extend({
isAlive:true
});
Em.Application.initializer({
name: "ioc",
initialize: function(container, application) {
container.register('session:instance', App.Session);
container.optionsForType('session', { singleton: true });
// inject session in all controllers
container.typeInjection('controller', 'session', 'session:instance');
}
});
//=====================================
// Test :
//=====================================
App.setupForTesting();
(function(){
var container, indexCtrl, session;
module('Test suite',{
setup:function(){
container = new Em.Container();
container.register('session:instance', Em.Object, {singleton:true});
container.register('controller:index', App.IndexController);
container.register('controller:application', Em.Object);
indexCtrl = container.lookup('controller:index');
session = container.lookup('session:instance');
}
});
test('IndexController IOC tests',function(){
ok(indexCtrl.get('controllers.application') !== undefined,
"ApplicationController should not be undefined");
ok(indexCtrl.get('session') !== undefined,
"Session should not be undefined");
});
})();
在此处提供的运行演示中:http ://emberjs.jsbin.com/AjoRUC/28/edit?js,output 您看到“会话”属性未正确模拟,并且未定义。