角度单位测试还是新手。我在模块'example'中有一个服务,它通过$ http服务加载一个本地JSON文件,并异步返回响应数据。
我发现我需要测试(使用Jasmine)
我的服务代码
/**
* Service to load JSON data.
*/
.service('jsonLoader', ['$http','$timeout', 'TABLE_DATA_LOC', function($http, $timeout, TABLE_DATA_LOC) {
this.load = function() {
return $timeout(function() {
return $http.get(TABLE_DATA_LOC).then(function(response) {
return response.data;
});
}, 30);
};
我目前的测试内容:
describe('jsonLoader service', function() {
var jsonLoader, httpBackend;
beforeEach(module("example"));
beforeEach(inject(function(_jsonLoader_, $httpBackend) {
jsonLoader = _jsonLoader_;
httpBackend = $httpBackend;
}));
it("should load json", function() {
httpBackend.whenGET('./mock/sample.json').respond({
"people": [
{
"person": {
"firstName": "jim",
"lastName": "bob"
}
}
]
});
});
});
是第一部分,我将如何使用jasmine来测试异步承诺?
答案 0 :(得分:1)
继续我的评论之后,我将采用这种方法。
describe('jsonLoader service', function() {
var uri;
beforeEach(module('example', function($provide) {
$provide.constant('TABLE_DATA_LOC', uri = 'mock/sample.json');
}));
it('should load JSON in a $timeout and return the response data', inject(function($httpBackend, $timeout, jsonLoader) {
var responseData = 'whatever', resolved = false;
$httpBackend.expectGET(uri).respond(responseData);
jsonLoader.load().then(function(data) {
expect(data).toBe(responseData);
resolved = true;
});
$timeout.flush();
$timeout.verifyNoPendingTasks();
expect(resolved).toBeFalsy();
$httpBackend.flush();
$httpBackend.verifyNoOutstandingRequest();
expect(resolved).toBeTruthy();
}));
});
Plunker demo〜http://plnkr.co/edit/jmc9FWjbOkpmT6Lu8kVn?p=preview