【发布时间】:2018-06-14 13:39:38
【问题描述】:
我有一个如下所示的组件,并且想测试$onChange 方法在绑定myBinding 发生变化时的作用。
我尝试了整个上午,但找不到解决此问题的方法。
angular
.module('project.myComponent', [])
.component('myComponent', {
bindings: {
myBinding: '<'
},
template: '<div>{{$ctrl.result}}</div>',
controller: myComponentController
});
function myComponentController($filter, someService) {
var ctrl = this;
ctrl.result = 0;
$ctrl.$onChange = function (changes) {
if(angular.isDefined(changes.myBinding)) {
if(angular.isDefined(changes.myBinding.currentValue)) {
if(angular.isDefined(changes.myBinding.currentValue != changes.myBinding.previousValue)) {
myService.doSomething(changes.myBinding.currentValue).then(
function(data) {
ctrl.result = changes.myBinding.currentValue * 3;
}
);
}
}
}
}
}
我希望我的测试表现得像改变绑定值的父组件一样。
require('angular-mocks');
describe('myComponment', function() {
var element, scope;
beforeEach(inject(function(_$rootScope_, _$compile_) {
}));
fit('should display the controller defined title', function() {
// prepare test and set myBinding to 10
expect(component.result).toBe(30);
});
});
这可能吗?如何? 有什么提示吗? Plunker、CodePen 还是其他示例?
【问题讨论】:
-
从 var element = angular.element('
') 开始; var compiledEl = injector.get('$compile')(element)($scope); var controller = compiledEl.controller('myComponent')
标签: angularjs unit-testing jasmine components angularjs-components