[英]Not getting json response from unit test in karma jasmine in angularjs?
describe('getEmployeeDetails', function () {
var getEmployeeDetails, httpBackend;
//2.
beforeEach(function () {
//3. load the module.
module('nodeApp');
// 4. get your service, also get $httpBackend
// $httpBackend will be a mock.
inject(function ($httpBackend, _getEmployeeDetails_) {
getEmployeeDetails = _getEmployeeDetails_;
httpBackend = $httpBackend;
});
});
// 5. make sure no expectations were missed in your tests.
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
//6.
it('ServiceTestSpec', function () {
var returnData = {};
//7. expectGET to make sure this is called once.
httpBackend.expectGET("/employee/getEmployeeDetails").respond(returnData);
//8. make the call.
var returnedPromise = getEmployeeDetails.getEmployees();
//9. set up a handler for the response, that will put the result
// into a variable in this scope for you to test.
var result;
returnedPromise.then(function (response) {
result = response.data;
});
//10. flush the backend to "execute" the request to do the expectedGET assertion.
httpBackend.flush();
//11. check the result.
expect(result).toEqual(returnData);
});
這是我用業力茉莉花寫的單元測試。 我正在chrome控制台中調試此單元測試,但“響應”對象為空。
我使用$ httpBackend來偽造HTTP請求。 那是我沒有得到響應對象的原因嗎?
但我正在通過測試成功。 還有一件事是:這是好習慣嗎? 要在angularJS中編寫單元測試?
默認情況下,angularJS Karma測試會阻止$ http請求,因此您不會獲得json響應。 要獲取響應,而不是附加.respond(yourFakeResponse)
,請使用.passThrough()
,它將發出預期的請求。
但是,我認為這並不是一個好習慣,因為測試現在依賴於外部資源,例如,在這種情況下,您的json文件或任何其他外部API等。由於外部資源中的問題也可能破壞測試,因此不再屬於單元測試的范疇,而更像是集成測試。
如您所做的那樣,最好在創建單獨的常量或服務文件以集中管理模擬響應數據的同時調用偽造的響應對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.