lundi 29 février 2016

AngularJS Karma Test ignore app initialization GET Request

I'm working on testing an angularjs factory/service which makes a GET request, but I'm running into an issue. When I call module('app'), our application makes a GET request for localization files, and I would like to be able to ignore/avoid this request when doing tests with $httpBackend. Is there a way to do this, or do I just have to expect the localization requests before each test?

Test Code:

/* global describe, beforeEach, afterEach, inject, it, expect, fdescribe, fit, browser, element, by */
'use strict';
describe('dataservice', function() {
   beforeEach(module('app'));

   var $httpBackend;

   beforeEach(inject(function($injector){
      $httpBackend = $injector.get('$httpBackend');
   }));

   afterEach(function(){
      $httpBackend.flush();
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
   });

   it('should form a request', function(){
      $httpBackend.expectGET('http://localhost:8080/api/data/data');
      dataservice.getData('data');
   });
});

Service Code:

/*jshint-W030*/

(function(){
   /* jshint expr:true */
   'use strict';
   angular
      .module('app')
      .factory('dataservice', dataservice);

   /* @ngInject */
   function dataservice($http){
      return{
         getData: getData
      };

      function getData(data){
         return $http.get('/api/data' + data)
            .then(getSuccess)
            .catch(getFailure);

         function getSuccess(response){
            return response;
         }

         function getFailure(error){
            return error;
         }
      }
   }
})();

app.controller.js:

(function () {
   'use strict';

   angular
      .module('app')
      .config(config)
      .controller('pageCtrl', pageCtrl)
      .controller('headerCtrl', headerCtrl);

   function config($translateProvider) {

      $translateProvider
         //...
         .useStaticFilesLoader({
            files: [{
               prefix: '/assets/lang/locale_',
               suffix: '.json'
            }]

         })
         .uniformLanguageTag('bcp47')
         .determinePreferredLanguage()
         .fallbackLanguage('en')
         .forceAsyncReload(true);
   }
   //...
})();

Aucun commentaire:

Enregistrer un commentaire