[英]Ajax unit test using Jasmine “TypeError: Cannot read property 'done' of undefined”
[英]Jasmine angular unit test 'Cannot read 'property' of undefined
我剛剛開始學習角度單元測試。 但是,此對具有 http 調用的函數的測試失敗。 我已經指出了這個問題,但我無法解決它。 我知道這是一些簡單的問題
控制器
//Get data from URL
vm.getJson = function() {
var url = 'https://www.reddit.com/r/worldnews/new.json',
count = 0;
$http.get(url).success(function(response) {
console.log(response);
for (var i = 0; i < response.data.children.length; i++) {
vm.data.push(response.data.children[i].data);
count++;
if (count === response.data.children.length) {
vm.numberOfPages();
}
}
vm.result = true;
}).error(function(err) {
console.log(err);
});
};
規格
//Testing the getJson function
describe('vm.getJson()', function() {
it('It should return dummy Data as response and vm.result to be truthy', function() {
var dummyData = {name: 'Umair'};
$httpBackend.whenRoute('GET','https://www.reddit.com/r/worldnews/new.json').respond(200, dummyData);
MainCtrl.getJson();
$httpBackend.flush();
expect(MainCtrl.result).toBeTruthy();
}); });
如果我從控制器函數中刪除循環,我不會收到任何錯誤並且測試通過。 我得到的錯誤是:
無法讀取 undefined 的“兒童” 。 從我附上響應數據的圖像來看,children 是數組。
當您的測試運行時, $httpBackend 實際上會攔截$http.get
調用並將dummyData
分配給響應,如您在
$httpBackend.whenRoute('GET','https://www.reddit.com/r/worldnews/new.json').respond(200, dummyData);
這種模擬行為允許您的單元測試快速完成,而無需依賴於從您的測試機器訪問 reddit。 因此,在您的控制器中, response.data = {name: 'Umair'}
並且該對象沒有名為children
。
為了解決這個問題,對於dummyData
,嘗試更多地模仿真實數據。
您在測試中返回一個具有屬性name
的對象,然后您嘗試訪問未定義的屬性data
。
您應該在測試中模擬真實的響應對象,例如:
var dummyData = {
data: {
children: [
{ data: 'foo'}
]
}
};
您 dummyData 不是數組,我想這可以解決問題,請嘗試以下測試
//Testing the getJson function
describe('vm.getJson()', function() {
it('It should return dummy Data as response and vm.result to be truthy', function() {
var dummyData = [{ data: 'Umair' }];
$httpBackend
.when('GET', 'https://www.reddit.com/r/worldnews/new.json')
.respond(.respond(
function() {
return [200, dummyData, {}];
}););
MainCtrl.getJson();
$httpBackend.flush();
expect(MainCtrl.result).toBeTruthy();
});
});
您應該在組件范圍內定義未定義的變量:
beforeEach(async () => {
fixture = TestBed.createComponent(ExportWizardComponent);
component = fixture.componentInstance;
// DEFINE VALUES FOR VARIABLES
component.patientInfo = Constants.PROJECT_WIZARD_INFO;
component.wizardMove = of(null);
fixture.detectChanges();
});
it('should create', async () => {
expect(component).toBeTruthy();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.