Angularjs $watch在我的测试中未被触发
这个问题我在网上已经见过很多次了,但我不知道我的情况到底出了什么问题 这是我的指令Angularjs $watch在我的测试中未被触发,angularjs,karma-jasmine,Angularjs,Karma Jasmine,这个问题我在网上已经见过很多次了,但我不知道我的情况到底出了什么问题 这是我的指令 angular.module('myApp') .directive('gsSpinner', function () { return { template: '<span><span ng-transclude></span><div class="gs-loader"><i class="fa fa-spinner fa-puls
angular.module('myApp')
.directive('gsSpinner', function () {
return {
template: '<span><span ng-transclude></span><div class="gs-loader"><i class="fa fa-spinner fa-pulse"></i></div></span>',
restrict: 'EAC',
transclude:true,
replace: false,
link: function(scope,element,attrs){
if ( element.is('.large')){
element.find('.gs-loader').addClass('large');
}
if ( element.is('.inline') ){
element.find('.gs-loader').addClass('inline');
}
scope.$watch(function(){ return attrs.gsSpinner; }, function(){
console.log('spinner attr changed', attrs.gsSpinner);
if ( !attrs || !attrs.gsSpinner || attrs.gsSpinner.length === 0 ){ // empty
return;
}
if ( attrs.gsSpinner === 'true' ){
element.addClass('gs-spinner-active');
}else{ // 'false'
element.removeClass('gs-spinner-active');
}
});
}
};
});
有人能帮忙吗?我在一个最小的测试项目中设置了您的代码,我看到每个测试用例有一个console.log(请参阅)。您没有看到console.log输出?抱歉-我需要指定的是,我看到的第一个打印是“hello”,而不是第二个打印是“true”。我希望看到属性变为“true”的打印-这是我在测试开始时所做的。顺便说一句-如果我监视$watch,我想我可以解决这个问题。。
describe('Directive: gsSpinner', function () {
// load the directive's module
beforeEach(module('myApp', 'backend-mock', 'templates-main'));
var element,
scope;
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
scope.active = 'foo';
element = angular.element('<div gs-spinner="hello" class="inline large"></div>');
element = $compile(element)(scope);
scope.$digest();
}));
describe('classes', function(){
it('should take class large and inline from parent and put it on gs-loader', function(){
var $gsLoader = element.find('.gs-loader');
expect($gsLoader.is('.large')).toBe(true);
expect($gsLoader.is('.inline')).toBe(true);
});
});
describe('active', function(){
it('should add gs-spinner-active on element', inject(function( $timeout, $rootScope ){
expect(element.is('.gs-spinner-active')).toBe(false);
angular.element('body').append(element);
scope.active = true;
element.scope().active = true;
element.scope().$apply();
scope.$digest();
scope.$apply();
element.scope().$digest();
element.scope().$apply();
element.children().scope().$apply();
element.children().scope().$digest();
$rootScope.$digest();
waitsFor(function(){
try{
$timeout.flush();
}catch(e){}
return element.is('.gs-spinner-active')
});
expect(element.is('.gs-spinner-active')).toBe(true);
}));
})