My Angular app's unit tests using Jest are giving me the error "TypeError: Cannot read property 'subscribe' of undefined". Despite searching online, none of the solutions provided seem to work for me. Below is some relevant code:
page-view.component.ts
@Input() gotPlot!: Observable<void>;
...
ngOnInit() {
this.initialiseColumnDefs();
this.gotPlot.subscribe((response) => { //The error occurs on this line
this.gotPlotValues(response);
});
}
page.component.ts
@Component({
selector: 'page',
template: `
<page-view
[gotPlot]="gotPlotSubject.asObservable()"
>
</page-view>
`,
})
export class PageComponent implements OnInit {
...
public gotPlotSubject: Subject<void> = new Subject<void>();
...
async get_plot(arr: any): Promise<any[]> {
//This function calls a service and gets 'plotValues'
(await this.service.get_plot(input)).subscribe((data: any) => {
//plotValues is set to values gotten from the service here
this.gotPlotSubject.next(plotValues);
});
}
}
page-view.component.spec.ts
@Component({
selector: 'page',
template: `
<page-view *ngIf="gotPlotSubject.asObservable()" [gotPlot]="gotPlotSubject.asObservable()">
</page-view>
`,
})
class PageMock {
public gotPlotSubject: Subject<void> = new Subject<void>();
constructor() {}
ngOnInit() {
let plotValues: any = [];
plotValues[0] = 1;
plotValues[1] = [1, 2, 3];
plotValues[2] = [2, 3, 4];
this.gotPlotSubject.next(plotValues);
}
}
describe('ViewComponent', () => {
let spectator: Spectator<ViewComponent>;
const createComponent = createComponentFactory({
component: ViewComponent,
declarations: [
ViewComponent,
PageMock,
],
imports: [TranslateModule.forRoot(), MaterialModule, AgGridModule, FormsModule],
providers: [HttpClient, HttpHandler, NGXLogger, NGXMapperService, HttpBackend, NGXLoggerHttpService, LoggerConfig],
schemas: [NO_ERRORS_SCHEMA],
});
beforeEach(() => {
spectator = createComponent();
});
it('should create', () => {
expect(spectator.component).toBeTruthy();
});
});
Could there be an issue with my PageMock setup? How can I properly mock the observable/subscribe functionality? Is there a more straightforward approach to handling this without relying so heavily on observables and subscribe? It seems like these features are complicating the Unit Testing process unnecessarily.