mardi 11 octobre 2016

Testing service that returns promise in Angular

I'm trying to test my services and the data they return. I'm using Angular, Typescript and Karma. This is my service

/// <reference path="../../../typings/index.d.ts" />

class WeatherDataService {

  static $inject = ['$http', '$log', '$q'];

  constructor(private $http: ng.IHttpService,
              private $log: ng.ILogService,
              private $q: ng.IQService) {
    this.$http = $http;
    this.$log = $log;
    this.$q = $q;
  }

  get(params: string): ng.IPromise<{}> {
    var self = this;
    var deferred = this.$q.defer();

    this.$http.get('http://ift.tt/1mGUATE?' + params + '&appid=' + API_KEY)
      .then((response) => {
        deferred.resolve(response.data);
      }, (errors) => {
        self.$log.debug(errors);
        deferred.reject(errors.data);
      });

    return deferred.promise;
  }
}

And this is the WeatherDataService.spec.ts

/// <reference path="../../../typings/index.d.ts" />

describe('WeatherDataService', () => {
  let weatherDataService;

  var $http, $log, $q;

  beforeEach(angular.mock.module('app'));

  beforeEach(inject(function (_$http_: ng.IHttpService, _$log_: ng.ILogService, _$q_: ng.IQService) {
    $http = _$http_;
    $log = _$log_;
    $q = _$q_;

    weatherDataService = new WeatherDataService($http, $log, $q);
  }));

  describe('testing karma', function () {
    it('Geolocation response should have a valid structure', function () {
      weatherDataService.get('lat=42.683529199999995&lon=26.309871599999997').then((response) => {
        expect(response).toBe('object');
      });
    });
  });
});

My main question is how to test the deferred.promise and check the structure of the received data.

Aucun commentaire:

Enregistrer un commentaire