单元测试失败:如何正确选择并单击组件按钮

时间:2019-02-13 17:01:53

标签: angular typescript jasmine karma-runner

我在这里进行单元测试:

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 :(得分:2)

您快到了,但是在检查方法是否已被调用之前,您需要等待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文件中使用automatic change detection

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

答案 1 :(得分:0)

我能想到的最简单的解决方案是:

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