16

我有一个简单的服务,我正在尝试对其进行单元测试。无论我尝试什么,searchService 要么是未知的提供者,要么 service 为空(奇怪的是这不会导致我的测试失败!!)。

任何人都知道我可能做错了什么?

angular.module('app').service('searchService', function( $q, _ ) { // _ is lodash

  var cache = [
    {
      id: "current",
      name: "Current",
      description: "Search current data"
    },
    {
      id: "historical",
      name: "Historical",
      description: "Search historical data"
    }
  ];

  this.getSearchOptions = function() {
    var deferred = $q.defer();
    deferred.resolve( angular.copy( cache ) );
    return( deferred.promise );
  };

  this.getSearchOptionsByID = function( id ) {
    var deferred = $q.defer();
    var searchOption = _.findWithProperty( cache, "id", id );

    if ( searchOption ) {
      deferred.resolve( angular.copy( searchOption ) );
    } else {
      deferred.reject();
    }
    return( deferred.promise );
   };
  }
);

我正在尝试创建一个加载到 searchService 中的单元测试,以便我可以检查缓存的值:

describe("Unit: Testing Services", function() {
  describe("Search Service:", function() {
    var service = null;

    beforeEach(function() {
      angular.module('app').service('_');
    });
    // I've also tried the commented out code below
    //beforeEach(inject(function(searchService) {
    //this.service = searchService;
    //}));
    //it('should contain an searchService', invoke(function(service) {

    it('should contain an searchService', function(searchService) {
      expect(searchService).not.to.equal(null);
    });

    it('should contain two search options', function(searchService) {
      expect(searchService.getSearchOptions()).to.equal(2);
    });
  });
});
4

1 回答 1

23

以下应该适用于没有参数的服务,也许这可以是一个起点:

describe("Unit: Testing Services", function() {
    describe("Search Service:", function() {

        beforeEach(function() {
            angular.module('app');
        });

        it('should contain a searchService',
           inject(function(searchService) {
                expect(searchService).not.to.equal(null);
        }));

        it('should contain two search options',
            inject(function(searchService) {
                expect(searchService.getSearchOptions()).to.equal(2);
        }));

   });
});

(您也可以在这里查看:如何使用 Jasmine 测试 AngularJS 服务?

于 2013-03-24T20:24:55.297 回答