【问题标题】:How to write unit test for method in Angular component using jasmine?如何使用茉莉花为Angular组件中的方法编写单元测试?
【发布时间】:2021-01-07 17:19:03
【问题描述】:

我是 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>

app.component.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 已被调用。

【问题讨论】:

  • 你遇到了什么错误?
  • @uminder: 预计间谍 uploadTemplate 已被调用。

标签: angular unit-testing jasmine karma-jasmine


【解决方案1】:

spy on 组件方法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();
  });
}));

【讨论】:

  • 首先比您花时间和快速响应,现在收到此错误错误:未捕获(承诺):错误:无法匹配任何路线。 URL 段:'uploadTemplate' 错误:无法匹配任何路由。 URL 段:'uploadTemplate'
  • 是的,您提供的解决方案完美运行谢谢。它涵盖了代码但仍然面临错误错误:未捕获(承诺):错误:无法匹配任何路由。 URL 段:'uploadTemplate'
  • 您是否也检查了我在之前评论中链接的答案?
  • 是的,但我不确定我需要做些什么改变?
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
相关资源
最近更新 更多