簡體   English   中英

如何使用 jasmine 為 Angular 組件中的方法編寫單元測試?

[英]How to write unit test for method in Angular component using jasmine?

我是 jasmine 單元測試的新手,但我不確定如何編寫以及它在 jasmine 中的工作方式。真的面臨很多錯誤。

誰能幫我為下面的代碼編寫單元測試?

app.component.html

<a href="" class="black" id="upload-template" (click)="uploadTemplate($event)" style="position: relative">
    <img style="width: 45px" src="/assets/images/icons/upload (1).png" alt="upload the model" />
    <div>Upload Template</div>
    <i *ngIf="uploadTempStatus" class="fas fa-check-circle fa-2x upload-check" aria-hidden="true"></i>
</a>

應用程序組件.ts

uploadTemplate(e) {
    e.preventDefault();
    this.clearMsg();
    if (this.selectedModel == null) {
        this.messageService.add({ severity: 'error', summary: 'Please option from dropdown', detail: 'Please contact Admin', sticky: true });
    } else if (this.selectedModel.name == 'Classification') {
        this.router.navigate(['router_one'], { state: { data: this.selectedModel } });
    } else {
        this.router.navigate(['router_two'], { state: { data: this.selectedModel } });
    }

} 

規格文件

  function newEvent(eventName: string) {
    const event = document.createEvent('CustomEvent');
    event.initCustomEvent(eventName, false, false, null);
    return event;
  }

  it('should be ok uploadTemplate', async(() => {
    const uploadT = fixture.debugElement.query(By.css('#upload-template'));
    expect(uploadT).toBeDefined();
    const uploadTNativeElement = uploadT.nativeElement;
    expect(uploadTNativeElement).toBeDefined();
    
    fixture.detectChanges();

    uploadTNativeElement.dispatchEvent(newEvent('click'));
    //uploadTNativeElement.dispatchEvent(new Event('click'));

    fixture.detectChanges();

    fixture.whenStable().then(() => {
      spyOn(component, 'uploadTemplate').and.callThrough();
      expect(component.uploadTemplate).toHaveBeenCalled();
    });
  }));

錯誤:預期間諜 uploadTemplate 已被調用。

監聽組件方法uploadTemplate必須在派發點擊事件之前創建。 嘗試更改單元測試如下:

it('should be ok uploadTemplate', async(() => {
  ...
  spyOn(component, 'uploadTemplate').and.callThrough();

  uploadTNativeElement.dispatchEvent(newEvent('click'));
  fixture.detectChanges();
  fixture.whenStable().then(() => {      
    expect(component.uploadTemplate).toHaveBeenCalled();
  });
}));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM