我正在编写一个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>
...测试通过!
答案 0 :(得分:0)
我基本上找到了一种解决方法,但我对此并不满意:
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));
});
看来,当我要加载网格数据时,网格尚未完全初始化。
答案 1 :(得分:0)
dx-data-grid小部件在setTimeout中从localStorage加载状态。尝试使用fakeAsync()和tick()来模拟测试中的时间。