问题
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