角单元测试测试组件方法

时间:2020-04-15 16:26:16

标签: angular unit-testing testing

我尝试测试组件方法。但是我无法调用它。

enter image description here

<!-- try to test addOrEditUser function -->
<table class="list" *ngIf="tableBody.length !== 0">
      <thead>
        <tr>
          <th *ngFor="let column of tableHeader">{{column.title}}</th>
        </tr>
      </thead>
      <tbody>
        <tr [ngClass]="checkClickability(row)" *ngFor="let row of tableBody" (click)="addOrEditUser(row)">
          <td class="inline" *ngFor="let d of row.slice(0, row.length - 1)">{{d}}</td>
          <td class="inline"><i class="fa fa-check" *ngIf="row[row.length - 1]"></i></td>
        </tr>
      </tbody>
</table>
// component
  public addOrEditUser(row: any[]): void {
    const isMember: boolean = row[row.length - 1];
    const profileId: string = row[0];

    // Do nothing if they are already a member
    if (isMember)
      return;
// component.spec.ts
  beforeEach(() => {
    fixture = TestBed.createComponent(QuickSearchPageComponent);
    component = fixture.componentInstance;
    component.createUserAttributes = attributeArray;
    component.existingUserAttributes = attributeArray;
    component.tableBody = tableBody;
    groupMembersService = TestBed.get(GroupMembersService);
    fixture.detectChanges();
  });

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

  it('should do nothing if row data is member', () => {
    spyOn(groupMembersService, 'addMembers');
    const tr: DebugElement[] = fixture.debugElement.queryAll(By.css('.search-page-table > table > tbody > tr'));
    tr[0].triggerEventHandler('click', null);  // 1. method 1, try to invoke it by triggerEventHandler
    component.addOrEditUser(tableBody[0]);     // 2. method 2, try to invoke it 
    expect(groupMembersService.addMembers).toHaveBeenCalled();
  });

我尝试通过两种方式调用component.addOrEditUser,单击元素并直接调用它。但是他们都没有工作。有人知道吗?

0 个答案:

没有答案