我正在使用基于Angular 12 的应用程序。我有一个名为notification
service 的服务,它处理来自ngx-toastr库的 toast 消息。
这是该服务的样子:
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,
});
}
}
服务方法运行良好,但是当我尝试为它们实施测试时,出现以下错误:
NotificationService should test "showSuccess" method FAILED
Error: <spyOn> : could not find an object to spy upon for success()
这些是测试:
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();
});
});
任何帮助表示赞赏。谢谢!