gpt4 book ai didi

angularjs - 如何在 angularJS 中为 $http.get 编写 karma-jasmine 测试用例?

转载 作者:可可西里 更新时间:2023-11-01 16:37:21 26 4
gpt4 key购买 nike

我有一个服务:

(function () {
angular.module('app').service('MyAppService', MyAppService);
MyAppService.$inject = ['$http', 'testUrl'];
function MyAppService($http, testUrl) {
var service = {
testFunction: testFunction
};
return service;
function testFunction() {
/*testurl is my backend API*/
return $http.get(testUrl)
.error(function(){
return;
})
.then(function (response) {
return response.data;
});
}
}
})();

我在我的 Controller 中称它为:

        testControllerFunction();
function testControllerFunction() {
MyAppService.testFunction().then(function (response) {
app.testResponse = response; //This my http response
console.log(app.testResponse);
});
}

我正在为 MyAppService 中成功的 $http.get 请求编写 karma 测试用例:

describe('MyAppService', function () {
var MyAppService,http;
beforeEach(function() {
module('app');
inject(function ($injector) {
MyAppService = $injector.get('MyAppService');
testUrl = $injector.get('testUrl');
http = $injector.get('$httpBackend');
});
});

it('should call the backend testurl ', function () {
MyAppService.testFunction();
http.expectGET(testUrl);
});
});

但这似乎不起作用?我哪里做错了?谢谢!

最佳答案

你必须 flush $httpBackend

    it('should call the backend testurl ', function () {
http.expectGET(testUrl);
MyAppService.testFunction();
http.flush();
});

关于angularjs - 如何在 angularJS 中为 $http.get 编写 karma-jasmine 测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31283730/

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