繁体   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