Angular Элементы меню модульного тестирования материала с asyn c loading - PullRequest
0 голосов
/ 27 февраля 2020

Я нашел много образцов для модульного тестирования с использованием Angular Материальных меню и предметов. Но я не могу найти никаких асин c труб в них.

Вот то, что я имею в качестве меню:

<!-- Options Button -->
<button id="divisionOptionsButton" *ngIf="!deleting && showEditBtn" mat-button
        [matMenuTriggerFor]="divisionCardMenu" #menuTrigger="matMenuTrigger">
  <mat-icon *ngIf="menuTrigger.menuOpen">arrow_drop_down</mat-icon>
  <mat-icon *ngIf="!menuTrigger.menuOpen">arrow_right</mat-icon>
  <span>Options</span>
</button>

<mat-menu #divisionCardMenu="matMenu" id="divisionOptionsMenuList" class="delete-menu card-actions-menu">
  <a mat-menu-item id="warehouseManageBtn" *ngIf="manageable"
     [routerLink]="['/organizations/' + item?.organization._id]" routerLinkActive="router-link-active">
    <mat-icon>settings</mat-icon>
    <span>Manage</span>
  </a>
  <mat-divider></mat-divider>
  <button id="warehouseEditBtn" mat-menu-item (click)="triggerEditEvent()">
    <mat-icon>edit</mat-icon>
    <span>Edit</span>
  </button>
  <button id="warehouseMoveBtn" mat-menu-item (click)="triggerMoveEvent()">
    <mat-icon>new_releases</mat-icon>
    <span>Move</span>
  </button>
  <mat-divider *ngIf="(['CADMIN', 'IADMIN'] | userRole | async)"></mat-divider>
  <button *ngIf="(['CADMIN'] | userRole | async)" id="warehouseDeleteBtn" mat-menu-item
          (click)="deleteDivision()" [disabled]="!canBeDeleted">
    <mat-icon>delete</mat-icon>
    <span>Delete</span>
  </button>
  <button *ngIf="(['CADMIN', 'IADMIN'] | userRole | async)"
          id="warehouseDeleteDesBtn" mat-menu-item (click)="deleteDivisionDes()" [disabled]="!desDataExists">
    <mat-icon>delete</mat-icon>
    <span>Delete Inspection Data</span>
  </button>
</mat-menu>

Вот как я инициализирую тесты:

    @Pipe({ name: 'userRole' })
class UserPipeStub implements PipeTransform {
  transform(role: any, ...args: any[]): any {
    return new Promise((resolve, reject) => {
      const userRoles = userRolesStub.userRoles();
      let hasAnyOfTheDesiredRoles;

      if (Array.isArray(role)) {
        hasAnyOfTheDesiredRoles = hasAnyRole(userRoles, role);
      } else {
        hasAnyOfTheDesiredRoles = hasRole(userRoles, role);
      }

      console.log(`Does user have any of the roles? ${hasAnyOfTheDesiredRoles}`);
      resolve(hasAnyOfTheDesiredRoles);
    });
  }
}

const userRolesStub = {
  userRoles: () => ['CADMIN', 'IADMIN']
};
@Component({
  template: `
    <app-division-card [item]="item" [showEditBtn]="showEditBtn" [manageable]="manageable" [doc]="doc"></app-division-card>
  `
})
class TestWrapperComponent {
  item: Division;
  doc: AngularFirestoreDocument<Division>;
  showEditBtn: boolean;
  manageable: boolean;
}

@Component({ template: '' })
class TestComponent {}
[...]
beforeEach(async(() => {
        TestBed.configureTestingModule({
          schemas: [CUSTOM_ELEMENTS_SCHEMA],
          declarations: [DivisionCardComponent, TestWrapperComponent, UserPipeStub],
          imports: [RouterTestingModule.withRoutes(testRoutes), MatMenuModule, NoopAnimationsModule],
          providers: [
            { provide: ComponentFixtureAutoDetect, useValue: true }
          ]
        }).compileComponents();
      }));

      beforeEach(() => {
        fixture = TestBed.createComponent(TestWrapperComponent);
        element = fixture.nativeElement;
        component = fixture.componentInstance;
      });

И это мой тест

it('should show confirmation dialog and delete', fakeAsync(() => {
  component.showEditBtn = true;
  fixture.detectChanges();

  const optionsBtnMenu = element.querySelector('#divisionOptionsButton');
  optionsBtnMenu.click();

  flush();
  fixture.detectChanges();

  const deleteBtn = fixture.debugElement.query(By.css('#warehouseDeleteBtn'));
  // const deleteBtn = element.parentNode.querySelector('#warehouseDeleteBtn');
  expect(deleteBtn).not.toBeNull();
  deleteBtn.triggerEventHandler('click', null);

  /*
        expect(matDialogStub.open).toHaveBeenCalled();
        expect(component.doc.delete).toHaveBeenCalled();
        */
}));

Ожидайте (deleteBtn) .not.toBeNull () каждый раз терпит неудачу. Я знаю, что меню открыто, потому что все остальные тесты, проверяющие их, проходят. Но только кнопки, показанные с разрешения, не работают, они всегда равны нулю. Я также знаю, что обещание выполнено, потому что я вижу журналы с

Что мне здесь не хватает?

...