我不明白为什么我的服务没有被调用。 在我的 BooklistComponent 中,我调用 ngOnInit ,它调用 initBooks() ,它调用 bookApiService getAll() 方法... 我的设置:
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [BookListComponent, BookCardComponent],
imports: [
HttpClientTestingModule
],
providers: [
BookApiService,
// MockProvider(BookApiService, {
// getAll: () => of<Book[]>([
// {
// title:"test",
// author: "Test",
// description: "hi",
// cover: 'empty',
// isbn: '12345',
// abstract: "test"
// }
// ]),
// })
],
}).compileComponents();
}));
const bookResolved = [{...}];
it('should call BookApiService getAll()', () => {
const spy_BookApiService_getAll = MockInstance(BookApiService, 'getAll', jasmine.createSpy('BookApiService.getAll')).and.returnValue(of(bookResolved));
const bookList = MockRender(BookListComponent).point.componentInstance;
bookList.ngOnInit();
expect(spy_BookApiService_getAll).toHaveBeenCalled();
})
BookComponent 中的 ngOnInit() 方法中调用了 getAll() 方法:
export class BookListComponent implements OnInit, OnDestroy {
books$!: Observable<Book[]>;
books!: Book[];
private sub?: Subscription;
constructor(private readonly bookApiService: BookApiService) { }
ngOnInit(): void {
this.initBooks();
}
initBooks() {
this.books$ = this.bookApiService.getAll();
}....
修复方法是调用
BookApiService.getAll
的初始代码,尽管安装了模拟:
const spy_BookApiService_getAll =
MockInstance(BookApiService, 'getAll', jasmine.createSpy())
.and.callThrough(); // <-- instead of `returnValue`.