ag-Grid:我如何对 ICellRendererAngularComp 进行单元测试

ag-Grid: How can I Unit test ICellRendererAngularComp

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

以下是我的代码块

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);

您可以为 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);
});