2016-11-28 79 views
0

我有一個單元測試無法正確讀取JSON的第二個請求角單元測試與多個expectGET在一個單一的測試

這是我的配置工廠

(function() { 
'use strict'; 

angular.module('commercial.factories').factory('config', config); 

function config($http) { 

    var service = { 
     GetConfig: getConfig 
    }; 

    return service; 

    function getConfig(identifier) { 
     var _config = {}; 

     // Check for url match in mapping json file 
     var urlMap = $http.get('./app/core/urlMap.json').then(function(response) { 
      for (var i = 0; i < response.data.length; i++) { 
       if (identifier.toString().toLowerCase().indexOf(response.data[i].url.toLowerCase()) > -1 || response.data[i].clientId === identifier) { 
        return response.data[i].contentFolder; 
       } 
      } 
     }); 

     // Retrieve the config for the related client found in the url map (above) 
     return urlMap.then(function(response) { 

      var contentFolder = response; 
      return $http.get('./content/' + response + '/config.json') 

      .then(function(response) { 

       if (Object.keys(_config).length === 0) { 
        _config = response.data; 
        _config.contentFolder = contentFolder; 
       } 

       return _config; 
      }); 
     }); 
    } 
} 
})(); 

和我的測試...

describe('Config Factory', function() { 

var configFactory; 

beforeEach(inject(function(_config_) { 
    configFactory = _config_; 
})); 

describe('GetConfig()', function() { 

    it('should get the urlMap from the urlMap.json', function() { 

     var identifier = '_default'; 
     var mockData = [{ url: identifier, contentFolder: '_default' }]; 

     $httpBackend.expectGET('./content/' + identifier + '/config.json'); 
     $httpBackend.expectGET('./app/core/urlMap.json').respond(mockData); 

     var promise = configFactory.GetConfig(identifier); 

     $httpBackend.flush(0); 

     promise.then(function(result) { 
      expect(result).toEqual(mockData); 
     }) 

    }); 
}); 

});

,並改掉閱讀config.json ...

{ 
    "clientId":34 
} 

當我運行我的測試中,我得到一個錯誤回來從卡拉馬說...

未捕獲的SyntaxError:意外的標記: 在我的JSON的第2行。

我很懷疑它可能與兩個expectGET在同一測試中有關係,但我無法確定嗎?

enter image description here

回答

0

您可能需要調用json.stringify(mockData)爲mockData,從GET請求響應時。 json解析器可能與mockData數組中的單引號有問題。

我也發現在你的期望缺少.

expect(result) toEqual(mockData);

應該是:

expect(result).toEqual(mockData);

+0

那會是響應還是toEqual? –

+0

我確實嘗試過,但我仍然得到相同的錯誤 –

0

OK,所以這是一個有點我的一個愚蠢的錯誤。

我注意到我沒有添加對config.json調用的響應。見下面的代碼。

it('should get the urlMap from the urlMap.json', function() { 

     var identifier = '_default'; 
     var mockData = [{ url: identifier, contentFolder: '_default' }]; 
     var mockConfig = { clientId: 34 }; 
     $httpBackend.expectGET('./app/core/urlMap.json').respond(mockData); 
     $httpBackend.expectGET('./content/' + identifier + '/config.json').respond(mockConfig); 

     var promise = configFactory.GetConfig(identifier); 

     $httpBackend.flush(); 

     promise.then(function(result) { 
      expect(result).toEqual(mockData); 
     }) 

    });