使用Jasmine测试一个简单的AngularJS服务

前端之家收集整理的这篇文章主要介绍了使用Jasmine测试一个简单的AngularJS服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个简单的服务,我正在尝试单元测试.无论我尝试什么,searchService是一个未知的提供者,或者服务是空的(这足以使我的测试失败!!).

任何人都有洞察我可能做错了什么?

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);
    });
  });
});
以下内容应该适用于没有参数的服务,也许这可以是一个起点:
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);
        }));

   });
});

(您也可以看看这里:How do I test an AngularJS service with Jasmine?)

原文链接:https://www.f2er.com/angularjs/142823.html

猜你在找的Angularjs相关文章