监视TestBed.createComponent()之前的组件方法

时间:2019-05-24 07:17:39

标签: angular typescript jasmine angular7

我正在使用AG-Grid,它提供了表初始化完成时的回调方法。

我需要确保在表完成初始化后调用此方法,但是我不确定该怎么做。该方法需要在实际创建组件之前进行侦听,因为它已经被调用而没有在我的测试中明确触发。

我尝试设置一个间谍,然后使用TestBed.createComponent()重新创建该组件,但是我不认为该间谍有效,因为它已挂接到先前创建的fixture.componentInstance中。

网格:

<ag-grid-angular 
  id="strategyListGrid"
  [rowData]="strategyList$ | async"
  [columnDefs]="columnDefs"
  (gridReady)="onGridReady($event)">
</ag-grid-angular>

组件功能:

/**
 * Fetch GridApi from initialized ag-grid
 * @param params GridEvent fired from component when initialization has completed
 */
onGridReady(params: GridReadyEvent) {
    this.gridApi = params.api;
    this.triggerTableResize();
}

测试代码:

function setup() {
    let fixture = TestBed.createComponent(StrategyListComponent);
    let app = fixture.componentInstance;
    return { app, fixture };
}

it('should resize the table when grid is ready', () => {
    const { fixture, app } = setup();
    let resizeSpy = spyOn(app, 'onGridReady');
    let fixtureRefresh = TestBed.createComponent(StrategyListComponent);
    fixtureRefresh.detectChanges();
    fixtureRefresh.whenStable().then(() => {
        expect(resizeSpy).toHaveBeenCalled();
    });
});

此操作失败,并显示: Expected spy onGridReady to have been called

我不认为这是在创建组件方法之前对其进行监视的正确方法。但是,如果是这样,有可能我需要使用fakeAsync等一下,然后再调用该方法。

编辑:我有一个工作版本,但不是很干净

it(
        'should resize the table when grid is ready',
        fakeAsync(() => {
            const { app, fixture } = setup();
            let gridReadySpy = spyOn(app, 'onGridReady');
            fixture.detectChanges();
            flush();

            fixture.whenStable().then(() => {
                fixture.detectChanges(); // Refresh template view
                flush();
                expect(gridReadySpy).toHaveBeenCalled();
            });
        })
    );

0 个答案:

没有答案