Javascript 如何对angularjs承诺进行单元测试
我希望您对这样的承诺进行单元测试:Javascript 如何对angularjs承诺进行单元测试,javascript,angularjs,unit-testing,Javascript,Angularjs,Unit Testing,我希望您对这样的承诺进行单元测试: 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
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;
}
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();
}));
});
这将返回对象的名称和数组。然后,我在控制器中通过简单调用getSongs函数来使用它:
var vm = this;
vm.songList = [];
vm.init = function () {
PlayerScreenService.getSongs()
.then(getSongsSuccess);
};
vm.init();
非常感谢。看一看。您的测试可能如下所示:
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;
}
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();
}));
});