I have a basic component class, inside ngOnInit it subscribes to a service call
ngOnInit() {
this.activityService.getActivities().subscribe(activities => {
console.log('inside sub');
this.recentActivities = activities;
});
}
So I included this console.log to see if this subscribe ever executes.
In my test I spyOn this activity service method to return an Observable collection of the data I need. Then in the test, I do the whole fixture.detectChanges() deal and expect my array to be of length 1.
fit('should populate recent activities', () => {
const activities = [new ActivityBuilder()
.withId('1').withRecentActivityActionId(RecentActivityActionType.Created).build()
];
spyOn(activityService, 'getActivities').and.returnValue(of(activities));
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
});
fixture.detectChanges();
expect(component.recentActivities.length).toBe(1);
});
According to the Angular docs, they pretty much do the same thing, I even tried the fakeAsync approach, but to no avail. What am I missing here? Why does the subscribe block not execute?
activityService
that was actually injected into the component being tested. – dmcgrandlefixture.detectChanges()
. The initial invocation triggers thengOnInit
behavior, which you need. However, any additional calls tofixture.detectChanges
are only relevant if you intend to make assertions about the rendered HTML (change detection in test specs is off by default). – ericksoen