我会对这样的承诺进行单元测试:
function getSongs() {
var d = $q.defer();
var URL = 'http://localhost:3002/songs';
$http({
method: 'GET',
url: URL
})
.success(function(data) {
d.resolve(data);
})
.error(function(data) {
d.reject(data);
});
return d.promise;
}
返回对象数组。然后我通过简单地调用getSongs函数在控制器中使用它:
var vm = this;
vm.songList = [];
vm.init = function () {
PlayerScreenService.getSongs()
.then(getSongsSuccess);
};
vm.init();
非常感谢。
答案 0 :(得分:2)
看看$httpBackend。您的测试看起来像这样:
describe('PlayerScreenService', function () {
it('should send HTTP request', inject(function (PlayerScreenService, $httpBackend) {
$httpBackend.whenGET('http://localhost:3002/songs').respond(200, {...});
var getSongsSuccess = jasmine.createSpy('getSongsSuccess');
var getSongsError = jasmine.createSpy('getSongsError');
PlayerScreenService.getSongs()
.then(getSongsSuccess, getSongsError);
$httpBackend.flush();
expect(getSongsSuccess).toHaveBeenCalledWith({...});
expect(getSongsError).not.toHaveBeenCalled();
}));
});