Reputation: 722
Normally when doing an expect that a mocked service call has been called it does it succesfully. I now have the following situation in which basically all code is getting triggered but the expect for the spy to have been called does not pass.
I use the latest Karma (4.1.0) and Jasmine (3.4.0) and a Angular 8.x version.
I have the following testBed configuration and an single testsuite.
fdescribe('DetailComponent', () => {
let component: DetailComponent;
let fixture: ComponentFixture<DetailComponent>;
let mockedResolvedData: TimesheetResolved;
let mockedTimesheet: Timesheet;
let mockedPermissions;
let mockTimesheetService;
let mockNotificationService;
let mockPermissionsService;
let mockRouter;
let mockActivatedRoute: ActivatedRoute;
beforeEach(async(() => {
mockedTimesheet = mockTimesheet();
mockedPermissions = mockPermissions();
mockedResolvedData = { timesheet: mockedTimesheet, error: null };
mockTimesheetService = jasmine.createSpyObj([
'patchTimesheet',
'getTimesheet',
]);
mockNotificationService = jasmine.createSpyObj(['showNotification']);
mockAuthenticationService = jasmine.createSpyObj(['getRole']);
TestBed.configureTestingModule({
imports: [
// left out MaterialDesign imports
NoopAnimationsModule,
FormsModule,
],
declarations: [
DetailComponent,
// list of MockComponents
],
providers: [
{ provide: TimesheetService, useValue: mockTimesheetService },
{ provide: NotificationService, useValue: mockNotificationService },
{ provide: AuthenticationService, useValue: mockAuthenticationService },
{ provide: NgxPermissionsService, useValue: mockPermissionsService },
],
});
mockRouter = TestBed.get(Router);
mockActivatedRoute = TestBed.get(ActivatedRoute);
}));
describe('when the resolvedData is filled: happy-flow (regular behavior)', () => {
beforeEach(() => {
fixture = TestBed.createComponent(TimesheetDetailComponent);
mockTimesheetService.getTimesheet.and.returnValue(of(mockedRefreshedTimesheet));
mockPermissionsService.getPermissions.and.returnValue(mockedPermissions);
mockTimesheetService.patchTimesheet.and.returnValue(of(new HttpResponse<Object>()));
component = fixture.componentInstance;
});
fit('should call the patch if the value from the remarkSubject is changed', () => {
// Arrange
fixture.detectChanges();
// Act
component.timesheetRemarksSubject.next('new value');
// Assert
expect(mockTimesheetService.patchTimesheet).toHaveBeenCalled();
});
});
The component has the following code:
// left out imports
@Component({
selector: 'detail-cmp',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.scss'],
})
export class DetailComponent implements OnInit, AfterViewInit, OnDestroy {
private readonly destroyed = new Subject();
timesheetRemarksSubject: Subject<string> = new Subject<string>();
timesheet: Timesheet;
constructor(
private readonly timesheetService: TimesheetService,
private readonly notificationService: NotificationService,
private readonly changeDetectorRef: ChangeDetectorRef,
) {}
ngOnInit(): void {;
this.route.data.subscribe(data => {
const resolvedData: TimesheetResolved = data['resolvedData'];
this.errorMessage = resolvedData.error;
this.onTimesheetReceived(resolvedData.timesheet);
});
}
onTimesheetReceived(timesheet: Timesheet): void {
this.timesheet = timesheet;
if (timesheet) {
// do something
}
}
ngAfterViewInit(): void {
if (this.timesheet) {
console.log('ngAfterViewInit!');
this.changeDetectorRef.detectChanges();
this.setupTimesheetRemarksSubjectSubscription();
}
}
private setupTimesheetRemarksSubjectSubscription(): void {
console.log('setupTimesheetRemarksSubjectSubscription');
this.timesheetRemarksSubject
.pipe(
takeUntil(this.destroyed),
debounceTime(500),
distinctUntilChanged(),
)
.subscribe(remark => {
console.log('succesfully remark object added');
console.log('value of the remark is: ', remark);
this.timesheet.remarks = remark;
this.patchTimesheetRemark();
});
}
ngOnDestroy(): void {
console.log('ngOnDestroy!');
this.destroyed.next();
this.destroyed.complete();
}
private patchTimesheetRemark(): void {
console.log('patching timesheet remarks!');
this.timesheetService.patchTimesheet(this.timesheet.id, this.timesheet.remarks).subscribe(
() => {
console.log('succesfully patched');
this.notificationService.showNotification(//custom message);
},
);
}
}
When making a custom out of the box component, barebones with the same kind of dependencies my spy is getting called... Which is weird because my setup is basically the same. https://stackblitz.com/edit/angular-bv7oj2 <- here is the barebones project. Probably best to just copy paste this in a barebones angular CLI project and run ng test
.
Bottomline is, something in my setup/configuration is different because in the barebones it works. The spy is getting called. In my own test it doesn't. I receive the following console logs:
this in combination with a failed test display:
I am a bit clueless in why the spy is not getting called. I left out of the most unimportant stuff out of the code, so if I'm missing something please tell me and I will provide.
Thanks in advance!
Upvotes: 1
Views: 1122
Reputation: 1659
Having an async test you need to make sure that the test waits especially if your test includes a debounceTime
. For that you can use a fakeAsync
test setup and call tick(500)
where the 500 is the time you have set as a debounce time.
The tick tells the test to actually wait for that debounceTime to be finished and only once that's over your spy gets invoked.
Have a look here: https://angular.io/api/core/testing/fakeAsync
Upvotes: 1