Trouble covering the following piece of code in spec file using karma and jasmine in angular 8
myMethod(id: number): boolean {
const data= this.myService.getSampleData();
return data.find(item => item.id === id).count;
}
spec:
it('should call myMethod ', () => {
spyOn(myService,'getSampleData').and.returnValue(of([{id:1,count:10}]))
component.myMethod(1);
});
It throws cannot read property .find of undefined. Although i tried spyOn(myService,'getSampleData').and.returnValue(of([{id:1,count:10}])) moving into beforeEach function as well but no luck
your method expects to get an array of items. however you return Observable < Array< Item>> from your spy. try this spyOn(myService,'getSampleData').and.returnValue([{id:1,count:10}])
The first issue is that you are returning an Observable using of
when the Service seems to return an array of items.
Second, you are not doing any expect to validate something in the test.
I would do this:
it('should call myMethod ', () => {
spyOn(myService,'getSampleData').and.returnValue([{id:1, count:10}]);
expect(component.myMethod(1)).toEqual(true);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.