MockService still causes error: Cannot read property 'subscribe' of undefined

风流意气都作罢 提交于 2021-01-27 07:27:17

问题


I'm new to Angular testing. So, I was following this pluralsight course.

I keep getting the same error

Cannot read property 'subscribe' of undefined

no matter what I do.

describe('AnnualReportComponent', () => {
   let fixture: ComponentFixture<AnnualReportComponent>;
   let mockReportService;
   let REPORTITEMS = [
     { id: 1, title: 'title 1' },
     { id: 2, title: 'title 2' },
     { id: 3, title: 'title 3' }
   ]

   beforeEach(() => {
    mockReportService = jasmine.createSpyObj('ReportService', ['getAnnualReport']);

    TestBed.configureTestingModule({
       imports: [FormsModule],
       declarations: [AnnualReportComponent], 
       providers: [
         { provide: ReportService, useValue: mockReportService }      
       ],
       schemas: [
         NO_ERRORS_SCHEMA
       ]
     });

     fixture = TestBed.createComponent(AnnualReportComponent);
     component = fixture.componentInstance;
   });  

    it('should create', () => {
      fixture.detectChanges(); 
      mockReportService.getAnnualReport.and.returnValue(of(REPORTITEMS));

        expect(component).toBeTruthy();
     });    
});

This is the component

export class AnnualReportComponent implements OnInit, OnChanges {
  ngOnInit() {
     this.getAnnualReport();
  }

   getAnnualReport () {
      this.reportService
       .getAnnualReport(this.fiscalYear)
       .subscribe(item => {
          this.reportItems = item});
   }

}

I keep getting this error:

TypeError: Cannot read property 'subscribe' of undefined
at AnnualReportComponent.getAnnualReport (webpack:///C:/../AnnualReportComponent.component.ts?:92:13)
at AnnualReportComponent.ngOnInit (webpack:///C:/../AnnualReportComponent.component.ts?:57:14)

This is my first work on Karma, but can't manage to run it. I don't know whether I missed something.

Thanks for helping.

来源:https://stackoverflow.com/questions/52134575/mockservice-still-causes-error-cannot-read-property-subscribe-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!