2015-10-28 27 views
0

我有一個在TypeScript中創建的Angular Service類,並且此服務有一個加載方法。這個特定的服務正在加載的列表實際上是硬編碼的,所以我不需要從任何後端服務加載它。我希望load方法返回一個承諾,因爲我想服務看起來像我在課堂上的其他數據服務。

下面是數據業務,我有

module MyApplication.Data { 

    export interface IDestinationService { 

     load(): ng.IPromise<Array<MyApplication.Models.Destination>>; 

    } 

    export class DestinationService implements IDestinationService { 

     items: Array<MyApplication.Models.Destination>; 

     constructor($http: ng.IHttpService, private $q: ng.IQService) { 
      this.items = new Array<MyApplication.Models.Destination>(); 
      this.items.push(new MyApplication.Models.Destination()); 
      this.items.push(new MyApplication.Models.Destination()); 
      this.items[0].Id = 2; 
      this.items[0].Description = 'Item 1'; 
      this.items[1].Id = 3; 
      this.items[1].Description = 'Item 2'; 
     } 

     load(): ng.IPromise<Array<MyApplication.Models.Destination>> { 
      var defer = this.$q.defer(); 

      defer.resolve(this.items); 

      return defer.promise; 
     } 

    } 

} 

從我讀這是什麼應該做服務工作。它將返回一個承諾,但承諾將在返回時立即解決,因此應該觸發該方法。

我有一個茉莉花測試類,如下所示:

module MyApplication.Tests { 

    describe('Data',() => { 

     describe('Destination',() => { 

      var $http: ng.IHttpService; 
      var $httpBackend: ng.IHttpBackendService; 
      var $q: ng.IQService; 

      beforeEach(inject((_$http_: ng.IHttpService, _$httpBackend_: ng.IHttpBackendService, _$q_: ng.IQService) => { 
       $http = _$http_; 
       $httpBackend = _$httpBackend_; 
       $q = _$q_; 
      })); 

      describe('',() => { 
       var results: Array<MyApplication.Models.Destination>; 

       beforeEach((done) => { 
        var service = new MyApplication.Data.DestinationService($http, $q); 
        service.load() 
         .then((result) => { 
          results = result; 
          done(); 
         }); 
       }); 

       it('Returns Planning Brokers list',() => { 
        expect(results.length).toBe(2); 
       }); 

      }); 

     }); 

    }); 

} 

但是當我運行這個測試,我從茉莉得到一個異步超時錯誤,因爲當時的方法不會被觸發。我怎樣才能讓它正常工作。

回答

1

您不應該需要第二個describebeforeEach塊。使用rootScope.$digest解決的承諾和重組這樣的測試代碼:

describe('Data',() => { 

    describe('Destination',() => { 

     var $http: ng.IHttpService; 
     var $httpBackend: ng.IHttpBackendService; 
     var $q: ng.IQService; 

     beforeEach(inject((_$http_: ng.IHttpService, _$httpBackend_: ng.IHttpBackendService, _$q_: ng.IQService) => { 
      $http = _$http_; 
      $httpBackend = _$httpBackend_; 
      $q = _$q_; 
     })); 

     it('Returns Planning Brokers list',() => { 
      var results: Array<MyApplication.Models.Destination>; 

      var service = new MyApplication.Data.DestinationService($http, $q); 
      service.load().then((results) => { 
       expect(results.length).toBe(2); 
      }); 

      $rootScope.$digest(); 
     }); 

    }); 

}); 
+0

你第一個例子沒有工作(重組的部分是好的,但它仍然沒有解決的承諾,但是,一旦我增加了$消化。它確實工作了。謝謝 –

+0

對不起,我在考慮第一個例子的es6承諾,我將刪除它。 – bgoerdt