Angular 8 测试 - Devextreme Grid getDataSource() 不使用状态存储

Angular 8 Testing - Devextreme Grid getDataSource() not Working with State Storing

我正在编写一个 Angular 8 测试来检查 dx-data-grid 是否正确列出并呈现数据。这是我的大致设置:

HTML

<dx-data-grid id="grid" [dataSource]="data">
  <dxo-state-storing [enabled]="true" type="localStorage" storageKey="storage-key"></dxo-state-storing>
  <dxi-column dataField="field1"></dxi-column>
  <dxi-column dataField="field2"></dxi-column>
</dx-data-grid>

打字稿

export class MyComponent {
    @Input() data;
}

测试

describe('MyComponent', () => {
    let component: MyComponent;
    let fixture: ComponentFixture<MyComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({ /* ... */ }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should list all items', () => {
        component.data= mockData;
        fixture.detectChanges();

        const gridElement = fixture.debugElement.query(
            By.css('#grid')
        );
        const dxGrid = <DxDataGridComponent>gridElement.componentInstance;
        dxGrid.instance.option('loadingTimeout', undefined);

        // Here is where the error occurs
        // dxGrid.instance.getDataSource() is undefined
        dxGrid.instance.getDataSource().load();

        const dataSource = dxGrid.dataSource;
        expect(dataSource.length).toBe(mockData.length);
        mockData.forEach(i => expect(dataSource).toContain(i));
    });

});

上面显示的测试失败并出现以下错误

TypeError: Cannot read property 'load' of undefined

但是,我们将从模板中删除以下 html:

<dxo-state-storing [enabled]="true" type="localStorage" storageKey="storage-key"></dxo-state-storing>

...测试通过!

我基本上找到了解决方法,但我对它不是很满意:

it('should list all items', async () => {
    component.data= mockData;
    fixture.detectChanges();

    // workaround
    await new Promise( resolve => setTimeout( () => resolve(), 0 ) );
    // ---

    const gridElement = fixture.debugElement.query(By.css('#grid'));
    const dxGrid = <DxDataGridComponent>gridElement.componentInstance;
    dxGrid.instance.option('loadingTimeout', undefined);
    dxGrid.instance.getDataSource().load();

    const dataSource = dxGrid.dataSource;
    expect(dataSource.length).toBe(mockData.length);
    mockData.forEach(i => expect(dataSource).toContain(i));
});

看起来,当我想加载它的数据时,网格没有完全初始化。

dx-data-grid 小部件在 setTimeout 中从 localStorage 加载状态。测试中尝试使用fakeAsync()和tick()模拟时间