模拟过滤器中使用的服务

时间:2015-09-15 19:17:45

标签: angularjs unit-testing jasmine

我正在为一个非常简单的过滤器编写单元测试:

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

我想模拟$sce服务并验证是否正在调用trustAsHtml方法。检查文档并没有给我带来太大的成功,经过大量的谷歌搜索,这是我能想到的最好的(仍然没有工作):

(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

1 个答案:

答案 0 :(得分: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);
    });
});