Angular test jasmine, ng-mocks

308 Views Asked by At

I don't understand why my service is not getting called.. in my BooklistComponent, I call ngOnInit which calls initBooks() which calls the bookApiService getAll() method... My Setup:

 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();
      })

The getAll() method is called in the ngOnInit() method in the BookComponent:

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();
  }....
1

There are 1 best solutions below

0
On BEST ANSWER

The fix is to call the initial code of BookApiService.getAll despite the installed mock on it:

const spy_BookApiService_getAll =
  MockInstance(BookApiService, 'getAll', jasmine.createSpy())
    .and.callThrough(); // <-- instead of `returnValue`.