测试 Angular 1.5 组件:如何测试 $onChanges
Testing Angular 1.5 components : how to test $onChanges
我想在创建控制器后测试组件的 $onChanges
$componentController
服务。但是我不知道如何 trigger/test $onChanges
。我试图更改传递给 $componentController
的绑定对象,但更改没有被选中。
然而,我能够使用旧的 $compile
& $rootScope
:
来做同样的事情
describe("test component", function() {
angular.module('test', []).component('component', {
template: '<span>{{$ctrl.text}}</span>',
bindings: {
'text': '@'
},
controller: function() {
this.$onChanges = function(changesObj) {
console.log("onChanges called", changesObj);
}
}
})
var $compile, $rootScope;
beforeEach(module('test'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
it('should call onChanges', function() {
var scope = $rootScope.$new()
scope.text = 'original text';
var el = $compile('<component text="{{text}}" />')(scope);
$rootScope.$apply();
console.log(el.find('span').text())
scope.text = 'text has changed';
$rootScope.$apply();
console.log(el.find('span').text())
})
})
我的问题是:在使用 $componentController
测试 $onChanges
时,是否必须手动调用 $onChanges
并手动构建 changesObj
?
是的,我想是的。它有助于专注于测试的意图。
如果您尝试一些最终会触发 onChanges 挂钩的高级操作,您实际上是在同时执行 Angular 和您的代码的内部行为。这可能不是您的本意。
确认您正在使用 Angular 并期待从这个钩子中得到一些特定的东西,明确地调用它是有意义的。
我想在创建控制器后测试组件的 $onChanges
$componentController
服务。但是我不知道如何 trigger/test $onChanges
。我试图更改传递给 $componentController
的绑定对象,但更改没有被选中。
然而,我能够使用旧的 $compile
& $rootScope
:
describe("test component", function() {
angular.module('test', []).component('component', {
template: '<span>{{$ctrl.text}}</span>',
bindings: {
'text': '@'
},
controller: function() {
this.$onChanges = function(changesObj) {
console.log("onChanges called", changesObj);
}
}
})
var $compile, $rootScope;
beforeEach(module('test'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
it('should call onChanges', function() {
var scope = $rootScope.$new()
scope.text = 'original text';
var el = $compile('<component text="{{text}}" />')(scope);
$rootScope.$apply();
console.log(el.find('span').text())
scope.text = 'text has changed';
$rootScope.$apply();
console.log(el.find('span').text())
})
})
我的问题是:在使用 $componentController
测试 $onChanges
时,是否必须手动调用 $onChanges
并手动构建 changesObj
?
是的,我想是的。它有助于专注于测试的意图。
如果您尝试一些最终会触发 onChanges 挂钩的高级操作,您实际上是在同时执行 Angular 和您的代码的内部行为。这可能不是您的本意。
确认您正在使用 Angular 并期待从这个钩子中得到一些特定的东西,明确地调用它是有意义的。