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