角度测试茉莉花,ng-mocks

问题描述 投票:0回答:1

我不明白为什么我的服务没有被调用。 在我的 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();
  }....
angular testing jasmine karma-runner ng-mocks
1个回答
0
投票

修复方法是调用

BookApiService.getAll
的初始代码,尽管安装了模拟:

const spy_BookApiService_getAll =
  MockInstance(BookApiService, 'getAll', jasmine.createSpy())
    .and.callThrough(); // <-- instead of `returnValue`.
© www.soinside.com 2019 - 2024. All rights reserved.