【问题标题】:Unit testing ag-grid in Angular 2Angular 2 中的单元测试 ag-grid
【发布时间】:2017-07-07 01:23:33
【问题描述】:

有人在 Angular 2 中对 ag-grid 组件进行单元测试吗?

对我来说,this.gridOptions.api 在测试用例运行时仍未定义。

【问题讨论】:

    标签: unit-testing angular ag-grid


    【解决方案1】:

    很抱歉参加聚会有点晚了,但我在几天前正在寻找这个问题的答案,所以想为最终来到这里的其他人留下答案。正如上面 Minh 所说,$digest 的现代等价物确实需要运行才能使 ag-grid api 可用。

    这是因为onGridReady() 运行后,您可以通过参数访问 api,如下所示。当带有网格的组件正在初始化时,它会自动运行。如果它在网格中定义(gridReady)="onGridReady($event)"

    public onGridReady(params)
    {
       this.gridOptions = params;
    }
    

    这意味着您现在可以访问this.gridOptions.api 并且它会被定义,您需要通过运行detectChanges() 在您的测试中重新创建它。这是我如何让它为我的项目工作的。

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    
    fixture.detectChanges(); // This will ensure the onGridReady(); is called
    

    这应该会导致在运行测试时定义.api。这是 Angular 6。

    有时测试可能需要执行等待或滴答:

      it('should test the grid', fakeAsync( async () => {
        // also try tick(ms) if a lot of data is being tested
        // try to keep test rows as short as possible
        // this line seems essential at times for onGridReady to be processed.
        await fixture.whenStable();
        // perform your expects...after the await
      }));
    

    【讨论】:

    • 有时你还需要使用一个 fakeAsync 调用,例如可能是一个 tick(10),甚至是一个 await fixture.whenStable() 子句来确保网格完全初始化。由于某种原因,网格需要几毫秒才能确定大小,然后它会调用 onGridReady。
    • 我没有尝试过,如果您认为它有用,请随时将其编辑为答案:-)
    • 我现在提供了更新。如果您还有其他 cmets,请重新编辑。
    • 可爱的东西 :-)
    【解决方案2】:

    如果您使用的是 ag-grid Enterprise,请确保在您的测试文件中包含 import 'ag-grid-enterprise'; 否则您将看到控制台错误并且永远不会调用 gridReady:

    Row Model "Server Side" not found. Please ensure the ag-Grid Enterprise Module @ag-grid-enterprise/server-side-row-model is registered.';
    

    【讨论】:

    • 我在角度测试 ag-grid 时遇到了同样的问题。网格可以正常工作,但是在 UT 期间它会抛出此错误。在 spec 文件中添加 importing ag-grid-enterprise 解决了这个问题。
    【解决方案3】:

    它仍然未定义,因为事件 onGridReady 尚未调用。我不确定 Angular 2,因为我使用 angularjs 并且必须执行 $digest 才能调用 onGridReady。

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 2021-04-03
      • 2018-05-01
      • 2016-12-10
      • 2018-10-26
      • 2021-12-16
      • 2020-03-10
      • 2019-02-02
      • 2019-05-13
      相关资源
      最近更新 更多