Boz*_*ski 5 karma-jasmine ag-grid angular angular-unit-test
我正在 Angular 中编写 Ag-grid 的单元测试用例,其中有 Angular Grid:外部过滤器,它是切换过滤器复选框。我收到“TypeError:无法读取未定义的属性‘onFilterChanged’”
我正在测试这个方法:
toggleCheckboxMethod({ checked }): void {
isChecked = checked;
this.gridApi.onFilterChanged(); //when this method initiates it causes for test to fail
}
Run Code Online (Sandbox Code Playgroud)
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
HttpClientModule,
HttpClientTestingModule,
AgGridModule.withComponents([]),
MatDialogModule,
BrowserAnimationsModule
],
declarations: [ TestComponent ],
providers: []
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should toggle checkbox', () => {
let isChecked = false;
spyOn(component, 'toggleCheckboxMethod').and.callThrough();
component.toggleCheckboxMethod({ checked: true });
expect(component.toggleCheckboxMethod).toHaveBeenCalled();
expect(isChecked).toEqual(true);
});
Run Code Online (Sandbox Code Playgroud)
我认为gridApi在你断言的那一刻是未定义的。测试ag-grid可能很奇怪,您必须等待其异步任务完成才能断言。
我会做这样的事情:
创建一个像这样的实用函数,您可以在继续之前等待某些事情成立:
import { interval } from 'rxjs';
.....
export const waitUntil = async (untilTruthy: Function): Promise<boolean> => {
while (!untilTruthy()) {
await interval(25).pipe(take(1)).toPromise();
}
return Promise.resolve(true);
};
Run Code Online (Sandbox Code Playgroud)
it('should toggle checkbox', async (done: DoneFn) => {
let isChecked = false;
spyOn(component, 'toggleCheckboxMethod').and.callThrough();
// wait until component.gridApi is truthy before carrying forward
await waitUntil(() => !!component.gridApi);
component.toggleCheckboxMethod({ checked: true });
expect(component.toggleCheckboxMethod).toHaveBeenCalled();
expect(isChecked).toEqual(true);
done(); // call done to let Jasmine know you're done (this could be optional)
});
Run Code Online (Sandbox Code Playgroud)
这是另一个与您有相同问题的人,如果您不喜欢我的解决方案,您可能需要检查答案的解决方案。
| 归档时间: |
|
| 查看次数: |
1208 次 |
| 最近记录: |