2015-09-15 40 views
2

我正在写一个单元测试一个非常简单的过滤器使用的服务:惩戒在过滤器

app.filter('htmlsafe', ['$sce', function($sce) { 
    return function(message) { 
    return $sce.trustAsHtml(message); 
    }; 
}]); 

我想嘲笑$sce服务并验证trustAsHtml方法被调用。检查文档并没有使我很成功,并经过大量使用Google,这是最好的,我可以想出(仍然没有工作):

(function (describe, it, expect, inject, beforeEach, module) { 
    describe('htmlsafe filter', function() { 
    var htmlsafe, $sce, untrustedString; 

    beforeEach(module('ComstackPmApp')); 

    beforeEach(function() { 
     module(function ($provide) { 
     $provide.service('$sce', $sce); 
     }); 
    }); 

    beforeEach(inject(function(htmlsafeFilter) { 
     htmlsafe = htmlsafeFilter; 
     untrustedString = '<p>Untrusted</p>'; 
     $sce = { 
     trustAsHtml: function() { 
      // stub method to spy on. 
     } 
     }; 
    })); 

    it('Should mark a string as HTML safe', function() { 
     spyOn($sce, 'trustAsHtml'); 
     htmlsafe(untrustedString); 

     expect($sce.trustAsHtml.calls.count()).toEqual(1); 
    }); 
    }); 
})(describe, it, expect, inject, beforeEach, angular.mock.module); 

然而,这给我留下了以下错误消息:

PhantomJS 1.9.8 (Mac OS X 0.0.0) htmlsafe filter Should mark a string as HTML safe FAILED 
TypeError: 'undefined' is not an object (evaluating '(isArray(Type) ? Type[Type.length - 1] : Type).prototype') 
undefined 
    at instantiate (bower_components/angular/angular.js:4480) 
    at bower_components/angular/angular.js:4341 
    at invoke (bower_components/angular/angular.js:4473) 
    at enforcedReturnValue (bower_components/angular/angular.js:4325) 
    at invoke (bower_components/angular/angular.js:4473) 
    at bower_components/angular/angular.js:4290 
    at getService (bower_components/angular/angular.js:4432) 
    at invoke (bower_components/angular/angular.js:4464) 
    at enforcedReturnValue (bower_components/angular/angular.js:4325) 
    at invoke (bower_components/angular/angular.js:4473) 
    at bower_components/angular/angular.js:4290 
    at getService (bower_components/angular/angular.js:4432) 
    at invoke (bower_components/angular/angular.js:4464) 
    at workFn (bower_components/angular-mocks/angular-mocks.js:2426) 
Error: spyOn could not find an object to spy upon for trustAsHtml() 
    at specs/filters/HtmlSafeFilter.js:26 

回答

2

不知道你想要做什么与所有的东西。您不需要提供$ sce服务:Angular提供它。你不必创造一个假的:只是窥视角提供的服务:

describe('htmlsafe filter', function() { 
    var htmlsafe, $sce, untrustedString; 

    beforeEach(module('ComstackPmApp')); 
    beforeEach(inject(function(_$sce_, htmlsafeFilter) { 
     htmlsafe = htmlsafeFilter; 
     untrustedString = '<p>Untrusted</p>'; 
     $sce = _$sce_; 
    })); 

    it('Should mark a string as HTML safe', function() { 
     spyOn($sce, 'trustAsHtml'); 
     htmlsafe(untrustedString); 

     expect($sce.trustAsHtml.calls.count()).toEqual(1); 
    }); 
}); 
+0

完美,谢谢。猜猜我需要刷上'inject'方法 - 我对角度很陌生,特别是单元测试。 –