1
我有一個AngularJS應用程序在測試中遇到了一些問題。AngularJS Karma測試「錯誤:意外的請求:GET」似乎沒有執行請求
方法
PlanService.prototype.getPlanList = function() {
this.activeRequest = true;
return this.PlanFactory.planList().then((function(_this) {
return function(response) {
_this.plans = response.plans;
return _this.activeRequest = false;
};
})(this));
};
return PlanService;
單元測試:
var planService;
beforeach(function() {
module("notRealModuleName");
inject(function(PlanService) {
planService = PlanService;
});
});
...(other tests)
it('should get a list of plans', function() {
var $httpBackend;
inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
});
var plans = {"plans": [array of stuff goes here]};
$httpBackend.whenGET('/plans/special').respond(plans);
var promise = planService.getPlanList();
promise.then(function(response) {
expect(response).toBeDefined();
expect(planService.plans).toBeDefined();
});
$httpBackend.flush();
});
當這個測試執行,錯誤Error: Unexpected request: GET http://ip_address/plans/special No more request expected
返回。如果我註釋掉httpBackend.flush
,測試通過。但是,如果我將expect(planService.plans)
更改爲不存在的方法,則不會失敗。顯然,期望沒有被調用。這有什麼問題?
作爲此響應的附錄:我們在此項目中使用路徑工廠。當路徑是硬指定的(即'/ plans/special')時,它似乎無法模擬whenGET。當使用路徑工廠值指定路徑時,它將起作用。我打算硬指定的路徑不包含服務器信息。因此,它達到了預期的模擬。感謝您的幫助,@ Boris-Charpentier! – CitizenX 2015-02-09 14:56:09
當Karma獲取API GET調用之前需要進行身份驗證時,也可能發生這種情況。 – 2017-03-26 13:36:29