I am working with an app based on Angular 12. I have service called notification
service which handles toast messages from ngx-toastr library.
This is how that service looks like:
export class NotificationService {
constructor(private toastr: ToastrService) {}
showSuccess(message: string = 'Success ', note: string = ''): void {
this.toastr.success(message, note);
}
showError(message: string = 'Error ', note: string = 'Try again'): void {
this.toastr.error(message, note, {
timeOut: 3000,
});
}
}
Service methods are working well, but when I am trying to implement tests for them then I get the following error:
NotificationService should test "showSuccess" method FAILED
Error: <spyOn> : could not find an object to spy upon for success()
These are the tests:
describe('NotificationService', () => {
let notificationService: NotificationService,
httpTestingController: HttpTestingController,
toastrService: ToastrService,
notificationServiceSpy: any;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CommonModule, HttpClientTestingModule, ToastrModule.forRoot()],
declarations: [],
providers: [{ provide: ToastrService, useValue: toastrService }],
}).compileComponents();
notificationService = TestBed.inject(NotificationService);
httpTestingController = TestBed.inject(HttpTestingController);
toastrService = TestBed.inject(ToastrService);
});
it('should be created', () => {
expect(notificationService).toBeTruthy();
});
it('should test "showSuccess" method', () => {
spyOn(toastrService, 'success').and.callThrough();
});
afterEach(() => {
httpTestingController.verify();
});
});
Any help is appreciated. Thanks!