2016-11-28 78 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); 
     }) 

    });