Как выполнить модульный тест в выпадающем меню, когда происходит событие нажатия - PullRequest
1 голос
/ 05 апреля 2019

Я запускаю модульный тест на угловом приложении. Когда я нажимаю на раскрывающееся меню, оно должно ответить обновлением данных внешнего интерфейса, таких как идентификационный номер

Frontend-template

<mat-menu #menuFilter="matMenu">
   <button *ngFor="let customer of customers; let i = index" 
   (click)="onCustomerChange(i)" mat-menu-item class="selectCustomerData"> 
   {{owner.id}}</button>
 </mat-menu>

Backend-typcript

onCustomerChange(i) {
    console.log(this.customers[i].ownerid);
    this.customerNumber = this.customers[i].ownerid;
    this.customerName = this.customers[i].ownername;
}

Тест для запуска

it('should update the customer number on selecting a value from drop down',()=>{
  fixture.detectChanges();
//what should I do here
 })

Ответы [ 2 ]

2 голосов
/ 05 апреля 2019

Для этого есть над чем поработать.

Сначала вы должны поставить id на кнопки вашего mat-menu, чтобы идентифицировать их по querySelector.Здесь я использую index с некоторой конкатенацией строк.Создайте свою собственную логику и следуйте ей в файле спецификации.Здесь я также изменил {{owner.id}} на {{customer.ownerid}}, так как я не знаю, на что ссылается owner.id, и это не относится к ответу.Также я добавил кнопку, чтобы вызвать меню, так как вы не упомянули, как это сделать.

<mat-menu #menuFilter="matMenu">
  <button *ngFor="let customer of customers; let i = index" [id]="'btn_'+i"
          (click)="onCustomerChange(i)" mat-menu-item class="selectCustomerData">
    {{customer.ownerid}}</button>
</mat-menu>

<!-- Refer to the spec.ts how to trigger this, since I don't know your logic.-->
<button mat-icon-button [matMenuTriggerFor]="menuFilter" id="btnMenu">
  Click Here to Trigger the Menu
</button>

Теперь spec.ts

let dom;
let button;
beforeEach(() => {
    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
   // You can initialize these here, if you are planning to use it inside the multiple 
   // test cases
    dom = fixture.nativeElement;
    button = dom.querySelector('#btnMenu');
    fixture.detectChanges();
  });

 it('should update the customer number on selecting a value from drop down', () => {
    // initially no mat-menu is opened
    let menu = dom.parentNode.querySelector('.mat-menu-panel');
    expect(menu).toBeFalsy();

    // trigger the menu
    button.click();

    // mat menu should be open now
    menu = dom.parentNode.querySelector('.mat-menu-panel');
    expect(menu).toBeTruthy();

    // click on the first element of the menu,it should pass the 0 index to the 
    // onCustomerChange method
    dom.parentNode.querySelector('#btn_0').click();
    expect(component.customerNumber).toBe(component.customers[0].ownerid);
  });

Вы можете реализовать это как 3разные тестовые случаи.Надеюсь, у вас есть идея.!

Наслаждайтесь !!

2 голосов
/ 05 апреля 2019

Хорошо, прежде всего, улучшение кода:

<mat-menu #menuFilter="matMenu">
   <button *ngFor="let customer of customers" 
   (click)="onCustomerChange(customer)" mat-menu-item class="selectCustomerData"> 
   {{owner.id}}</button>
 </mat-menu>

и в тс:

onCustomerChange(customerObj) {
   console.log(customerObj.ownerid);
   this.customerNumber = customerObj.ownerid;
   this.customerName = customerObj.ownername;
}

Теперь для юнит-теста:

  it('should update the customer number on selecting a value from drop down', () => {
    component.customers = [{ ownerid: 1, ownerName: 'Person1' }, { ownerid: 2, ownerName: 'Person2' }];
    spyOn(component, 'onCustomerChange').and.callThrough();
    const e = fixture.debugElement.nativeElement.querySelectorAll('.selectCustomerData');
    e[1].click();
    expect(component.onCustomerChange).toHaveBeenCalledWith({ ownerid: 2, ownerName: 'Person2' });
    expect(component.customerNumber).toBe(2);
    expect(component.customerName).toBe('Person2');
  });

Вы можете обратиться к этому блогу, чтобы получить очень сложные примеры в Angular Unit Testing.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...