gpt4 book ai didi

javascript - 如何对 angularjs promise 进行单元测试

转载 作者:行者123 更新时间:2023-11-29 21:46:55 26 4
gpt4 key购买 nike

我希望你对这样的 promise 进行单元测试:

 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 函数在 Controller 中使用它:

var vm = this;

vm.songList = [];

vm.init = function () {
PlayerScreenService.getSongs()
.then(getSongsSuccess);
};

vm.init();

非常感谢。

最佳答案

看看$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();
}));

});

关于javascript - 如何对 angularjs promise 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30813652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com