我有一個為兩種方法撰寫的基本單元測驗用例。
it('should populateChartDatasets call getColorCodes', () => {
component.chartConfig = mockChartConfig;
spyOn(component, 'getColorCodes');
component.populateChartDatasets(filteredTreatments, filteredYears);
expect(component.getColorCodes).toHaveBeenCalled();
});
方法populateChartDatasets首先應該colorCode從方法中選擇,getColorCodes然后將準備好的資料集推送到chartConfig.data.datasets.
命令后一切正常ng serve
但是這個測驗用例失敗了,下面拋出了錯誤
should populateChartDatasets call getColorCodes FAILED
TypeError: Cannot read properties of undefined (reading '0')
在 method 內部populateChartDatasets,這條線this.chartConfig.data.datasets.push({})失敗了,因為似乎下面的方法component.chartConfig = mockChartConfig不會等待這個分配給 chartConfig 物件,這就是為什么data.datasets拋出未定義的原因。
我給出了setTimeout 500ms解決問題的方法(至少成功但控制臺中拋出了另一個錯誤)
it('should populateChartDatasets call getColorCodes', () => {
component.chartConfig = mockChartConfig;
setTimeout(() => {
spyOn(component, 'getColorCodes');
component.populateChartDatasets(filteredTreatments, filteredYears);
expect(component.getColorCodes).toHaveBeenCalled();
}, 500);
});
Spies must be created in a before function or a spec
我怎樣才能使這個測驗通過?
Stackblitz 示例:https ://stackblitz.com/edit/unit-test-template-337ysq?file=src/app/app.component.spec.ts
uj5u.com熱心網友回復:
這里只有一個問題,所以當你在內部呼叫“populateChartDatasets”方法時,它依賴于“getColorCodes”方法來回傳一個字串。如果沒有這個程序,“populateChartDatasets”方法永遠不會完成。要解決這個問題,你可以這樣做 -
it('should populateChartDatasets call getColorCodes', () => {
spyOn(component, 'getColorCodes').and.callFake(d => {
return "#ffffff"
});
component.populateChartDatasets(filteredTreatments, filteredYears);
expect(component.getColorCodes).toHaveBeenCalled();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427118.html
