Сбой модульного теста: как правильно выбрать и нажать кнопку компонентов - PullRequest
0 голосов
/ 13 февраля 2019

У меня есть модульный тест здесь:

fit('should call getImageByID upon submit when a search id is present', () => {
    spyOn(component, 'getImageById');
    component.searchId = '1';
    submit = fixture.debugElement.query(By.css('#getimagebyid')).nativeElement;
    submit.click();
    expect(component.getImageById).toHaveBeenCalled();
  });

Модульный тест не пройден, так как ожидание не выполнено (метод не выполняется), что мне не хватает?Вот метод компонента, который не запускается:

getImageById() {
        this.imageAPIService.getImage(this.searchId).subscribe(res => {
            this.response.id = (res as any).id;
            this.response.image = (res as any).image;
        });
    }

и html для компонента:

<h4>Browse Images</h4>
<div class="row">
    <img *ngIf="response.id != null" [src]="response.image[0].url" height="200">
</div>
<div class="row">
    <input [(ngModel)]="searchId" type="text">
    <button class="btn btn-block btn-primary" id="getimagebyid" [disabled]="!searchId" (click)="getImageById(searchId)">Search</button>
</div>

Ответы [ 2 ]

0 голосов
/ 13 февраля 2019

Самое простое решение, о котором я могу подумать:

it('should call getImageByID upon submit when a search id is present', () => {
  const spy = spyOn(component, 'getImageById');
  fixture.debugElement.query(By.css('#getimagebyid'))
    .triggerEventHandler('click', null);
  expect(spy).toHaveBeenCalledTimes(1);
});
0 голосов
/ 13 февраля 2019

Вы почти у цели, но вам нужно будет дождаться обработки события click, прежде чем проверять, был ли вызван метод.

1) Самый прямой способ сделать это - вызвать detectChanges () для явной активации обнаружения изменений.

it('clicking on settings icon will trigger openModal method', () => {
  spyOn(component, 'getImageById');
  component.searchId = '1';
  submit = fixture.debugElement.query(By.css('#getimagebyid')).nativeElement;
  submit.click();
  fixture.detectChanges();
  expect(component.getImageById).toHaveBeenCalled();
  });

2) В качестве альтернативы, вы можете использовать автоматическое обнаружение изменений в вашем файле .spec.

 import { ComponentFixtureAutoDetect, . . . . } from '@angular/core/testing';
.
.
TestBed.configureTestingModule({
  declarations: [ BannerComponent ],
  providers: [
    { provide: ComponentFixtureAutoDetect, useValue: true }
  ]
});

3) Обработайте его с помощью функции async () для обработки события асинхронного нажатия кнопки.Затем следует вызов .whenStable(), который возвращает обещание.

import { async, . . . . } from '@angular/core/testing';
.
.
it('clicking on settings icon will trigger openModal method', async(() => {
  spyOn(component, 'getImageById');
  component.searchId = '1';
  submit = fixture.debugElement.query(By.css('#getimagebyid')).nativeElement;
  submit.click();

  fixture.whenStable().then(() => {
    expect(component.getImageById).toHaveBeenCalled();
  });
}));
...