【问题标题】:ag-Grid: How can I Unit test ICellRendererAngularCompag-Grid:我如何对 ICellRendererAngularComp 进行单元测试
【发布时间】:2021-12-17 11:33:23
【问题描述】:

我创建了一个自定义控件,它通过一组操作从 ag-grid 实现 ICellRendererAngularComp 并将其注入到我的 ag-grid 主组件中,但我不确定如何为自定义控件编写测试模拟params 我们是否有任何需要导入的预定义类或模块

以下是我的代码块

import { Component } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';

@Component({
  template: ` <button
    type="button"
    class="btn btn-primary btn-xs"
    title="Copy"
    (click)="triggerAction('copy')"
  >
    <i class="fa fa-copy"></i>
  </button>`
})

export class GridButtonsComponent
  implements ICellRendererAngularComp
{
  public params: any;

  agInit(params: any): void {
    this.params = params;
  }

  refresh(): boolean {
    return false;
  }

  public triggerAction(actionType: string) {
    this.params.data.actionType = actionType; // custom property added
    this.params.clicked(this.params.data);
  }
}

以下是我尝试过的测试

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [GridButtonsComponent]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(GridButtonsComponent);
    component = fixture.componentInstance;
    let params = {
      column: 'status',
      value: 'test-value',
      data: {
        actionType: ''
      }
    };
    component.agInit(params);
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should return false for refresh', () => {
    expect(component.refresh()).toBe(false);
  });

  it('should actionType be as input passed', () => {
    component.triggerAction('edit');
    expect(component.params.data.actionType).toBe('edit');
  });
});

在最后一次测试中,我不确定如何模拟 this.params.clicked(this.params.data);

【问题讨论】:

    标签: angular ag-grid ag-grid-angular


    【解决方案1】:

    您可以为params 附加一个模拟函数。

    let params = {
      column: 'status',
      value: 'test-value',
      data: {
        actionType: ''
      },
      clicked: function () { }
    };
    

    然后断言clicked函数是否以这种方式被调用。不言自明..

    it('should actionType be as input passed', () => {
      spyOn(params, 'clicked').and.callThrough();
      component.triggerAction('edit');
      expect(component.params.data.actionType).toBe('edit');
      expect(params.clicked).toHaveBeenCalledWith(params.data);
    });
    

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 2017-07-07
      • 2021-01-15
      • 2012-01-08
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2020-06-28
      相关资源
      最近更新 更多