我正在尝试测试驱动绑定(bind)到指令的 Controller 。
app.module('App')
.directive('myDirective', function() {
return {
templateUrl: '../my-directive.html',
scope: true,
bindToController: {
model: '='
},
controller: 'DirectiveCtrl as DirectiveCtrl'
};
})
.controller('DirectiveCtrl', function() {
var DirectiveCtrl = this,
model = DirectiveCtrl.model;
DirectiveCtrl.resetValue = function() {
DirectiveCtrl.model = model;
};
});
在测试中,
describe('DirectiveCtrl', function() {
var DirectiveCtrl,
model = {
id: 'id',
name: 'name'
};
beforeEach(module('App'));
beforeEach(inject(function($controller) {
DirectiveCtrl = $controller('DirectiveCtrl');
// code to initialize controller with model value;
}));
it('resets the default value', function() {
DirectiveCtrl.resetValue();
expect(DirectiveCtrl.model).toEqual(model);
});
});
我想以与有界 Controller 在指令编译期间的行为类似的方式初始化 Controller 。我怎样才能做到这一点?
最佳答案
我终于在 Angular 中找到了解决方案 $controller decorator 。第二个参数采用具有绑定(bind)值的对象。
所以测试是,
describe('DirectiveCtrl', function() {
var DirectiveCtrl,
model = {
id: 'id',
name: 'name'
};
beforeEach(module('App'));
beforeEach(inject(function($controller) {
DirectiveCtrl = $controller('DirectiveCtrl', {
model: model
});
}));
it('resets the default value', function() {
DirectiveCtrl.resetValue();
expect(DirectiveCtrl.model).toEqual(model);
});
});
关于javascript - 在单元测试时用值实例化绑定(bind) Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35897077/