![](/img/trans.png)
[英]How to test .subscribe method using jasmine karma unit testing where angular components is interacting with service?
[英]Covering unit test for array with .find method in angular using karma and jasmine
無法在 angular 8 中使用 karma 和 jasmine 在規范文件中覆蓋以下代碼段
myMethod(id: number): boolean {
const data= this.myService.getSampleData();
return data.find(item => item.id === id).count;
}
規格:
it('should call myMethod ', () => {
spyOn(myService,'getSampleData').and.returnValue(of([{id:1,count:10}]))
component.myMethod(1);
});
它拋出無法讀取未定義的屬性 .find。 雖然我試過 spyOn(myService,'getSampleData').and.returnValue(of([{id:1,count:10}])) 進入 beforeEach 函數,但沒有運氣
您的方法期望獲得一組項目。 但是你從你的間諜那里返回 Observable < Array< Item>> 。 試試這個spyOn(myService,'getSampleData').and.returnValue([{id:1,count:10}])
第一個問題是,你正在使用返回一個可觀察of
,當服務似乎返回項目的數組。
其次,您沒有做任何期望來驗證測試中的某些內容。
我會這樣做:
it('should call myMethod ', () => {
spyOn(myService,'getSampleData').and.returnValue([{id:1, count:10}]);
expect(component.myMethod(1)).toEqual(true);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.