我有一个单元测试无法正确读取第二个请求中的JSON
这是我的Config工厂
(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有关,但我无法确定?
答案 0 :(得分:0)
当从get请求响应时,您可能需要为mockData调用json.stringify(mockData)
。 json解析器可能在mockData数组中有单引号问题。
我还发现了你期望的遗失.
:
expect(result) toEqual(mockData);
应该是:
expect(result).toEqual(mockData);
答案 1 :(得分:0)
好的,所以这对我来说是一个愚蠢的错误。
我注意到我没有添加对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);
})
});