2016-06-13 4 views
0

У меня есть простой сервис здесь, когда я тестирую и продолжаю получать вышеуказанную ошибку. Сделал много исследований и знаю, что у меня есть что-то, что является нулевым в моем коде, но я не могу его найти. Мысли? Заранее спасибо :)«ТипError: undefined не является объектом» при попытке тестирования службы

config.js

'use strict';  

angular.module('App').service('configService', function(
    $rootScope, $http) { 
    var configObj = null; 
    return { 

    getConfig: function() { 
     if (configObj != null) { 
     console.log("returning cached config"); 
     return configObj; 
     } 
     else { 
     $http.get('conf.json').then(function(res) { 
      $http.get(res.confLocation).then(function(
      locationResponse) { 
      configObj = locationResponse; 
      $rootScope.configObj = configObj; 
      console.log($rootScope.configObj); 
      return configObj; 
      }); 
     }); 
     } 
    } 
    }; 
}); 

ConfigTest.js

'use strict'; 

describe('Service: configService', function() { 

    // load the controller's module 
    beforeEach(module('App')); 

    var configService, $httpBackend, results; 
    var tstConfig = { 
    "confLocation": "local-dev-conf.json" 
    }; 
    var tstConfigObj = { 
    "AWS": { 
     "region": "us-east-1", 
     "endpoint": "http://localhost:8133" 
    } 
    }; 

    // Initialize the controller and a mock scope 
    beforeEach(inject(function(_configService_, _$httpBackend_) { 
    inject(function($rootScope) { 
     $rootScope.USERNAME = 'TESTER'; 
     $rootScope.configObj = tstConfigObj; 
    }); 

    configService = configService; 
    $httpBackend = _$httpBackend_; 
    // backend definition common for all tests 
    $httpBackend.expectGET('conf.json').respond(tstConfig); 
    $httpBackend.expectGET('local-dev-conf.json').respond(tstConfigObj); 
    })); 

    it('it should do something', inject(function() { 

    results = configService.getConfig().then(function() { //ERROR HERE 

     // What should I be expecting to check if it's parsing the file? 
     // expect(configFile).toEqual("Object{AWS: Object{region: 'us-east-1', endpoint: 'http://localhost:8133'}}") 

     console.log(results); 
    }); 
    $httpBackend.flush(); 
    })); 
+1

строка кода 'configService = configService;' должна быть 'configService = _configService_;' – rob

+0

Эй, спасибо за ответ, к сожалению, я получаю ту же ошибку. «TypeError: undefined не является объектом (оценка« configService.getConfig(). Then ») (строка 83)« –

ответ

0

Проблема с вашим файлом спецификации/тестовый. Вам необходимо назначить configService - configService. Вместо этого вы назначаете configService на номер configService.

Также, поскольку вы вызываете метод getConfig из своего блока it, я предлагаю вам его spyOn. Но у вас нет шпиона. И он также должен вернуть функцию с именем then. Поскольку у вас этого нет, поэтому вы получаете неопределенную ошибку.

Ниже что-то для справки:

'use strict'; 

describe('Service: configService', function() { 

    // load the controller's module 
    beforeEach(module('App')); 

    var configService, $httpBackend, results; 
    var tstConfig = { 
    "confLocation": "local-dev-conf.json" 
    }; 
    var tstConfigObj = { 
    "AWS": { 
     "region": "us-east-1", 
     "endpoint": "http://localhost:8133" 
    } 
    }; 

    // Initialize the controller and a mock scope 
    beforeEach(inject(function(_configService_, _$httpBackend_) { 
    inject(function($rootScope) { 
     $rootScope.USERNAME = 'TESTER'; 
     $rootScope.configObj = tstConfigObj; 
    }); 

    configService = _configService_; 
    $httpBackend = _$httpBackend_; 
    // backend definition common for all tests 
    $httpBackend.expectGET('conf.json').respond(tstConfig); 
    $httpBackend.expectGET('local-dev-conf.json').respond(tstConfigObj); 

    spyOn(configService, 'getConfig').and.callFake(function(){ 
     return{ 
      then: function(){ 
       return "something"; 
      } 
     } 
    }); 

    })); 

    it('it should do something', inject(function() { 

     results = configService.getConfig().then(function() { //ERROR HERE 

      // What should I be expecting to check if it's parsing the file? 
      // expect(configFile).toEqual("Object{AWS: Object{region: 'us-east-1', endpoint: 'http://localhost:8133'}}") 

      console.log(results); 
     }); 
     //$httpBackend.flush(); 
    })); 

}); 

Надеется, что это помогает.

+0

Теперь он работает, спасибо! –

0

Это потому, что вы не возвращаете обещание в else заявлении config.js

'use strict';  

angular.module('App').service('configService', function(
    $rootScope, $http) { 
    var configObj = null; 
    return { 

    getConfig: function() { 
     if (configObj != null) { 
     console.log("returning cached config"); 
     return configObj; 
     } 
     else { 
     // return the promise here 
     return $http.get('conf.json').then(function(res) { 
      $http.get(res.confLocation).then(function(
      locationResponse) { 
      configObj = locationResponse; 
      $rootScope.configObj = configObj; 
      console.log($rootScope.configObj); 
      return configObj; 
      }); 
     }); 
     } 
    } 
    }; 
}); 

Вы забыли вернуть обещание, поэтому функция возвращается undefined, которая «не является объектом» и не имеет .then