0

在我的 Angular 12 应用程序中,我将 aChangeDetectionStrategy.OnPush用于我的组件,然后ChangeDetectorRef通过构造函数注入 a 。我想测试我的方法并确保我正在检测更改。它总是告诉我它没有被调用。

searchLabsByTextField(): void {
    this.roomService.search(this.searchText).subscribe({
        next: x => {
            ...
            this.cdr.detectChanges()
        }
    })
}

我不知道如何检查是否被调用,因为间谍似乎不适用于 ChangeDetectorRef。我尝试的是这样的:

let detectChangesSpy: SpyInstance

const createComponent = createRoutingFactory({
    component: HomeComponent,
    detectChanges: false,
    providers: [ChangeDetectorRef]
})

beforeEach(() => {
    spectator = createComponent()
    component = spectator.component

    const changeDetectorRef = spectator.fixture.debugElement.injector.get(ChangeDetectorRef)
    detectChangesSpy = jest.spyOn(changeDetectorRef, 'detectChanges')

    service = spectator.inject(RoomService)
    service.search.mockReturnValueOnce(of(new RoomSearchDTO()))
}

it('should xyz', fakeAsync(() => {
    component.searchLabsByTextField()
    expect(detectChangesSpy).toHaveBeenCalled()
}))
4

0 回答 0