【问题标题】:How to test a function in angular?如何以角度测试函数?
【发布时间】:2020-05-19 11:50:27
【问题描述】:

这是应用组件中非常简单的功能,需要为它编写测试用例。

我尝试过的代码。

app.component.html

<button
    class="click"
    (click)="clickHandler('dummy data')"
  >
    Click Here
  </button>

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'root-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}

clickHandler(value: string) {
    if (value) {
    }
  }
}

这是我为上述代码尝试过的测试,

app.component.spec.ts

  it('should check clickHandler function', fakeAsync(() => {
    spyOn(component, 'clickHandler');
    let button = fixture.debugElement.nativeElement.querySelector('button');
    button.click();
    fixture.detectChanges();
    tick();
    expect(component.clickHandler).toHaveBeenCalled();
  }));

我不确定是否需要检查功能是否存在。

需求:我需要编写测试用例来检查应用组件中的clickHandler函数。

我已经尝试了上述方法,这导致成功,但我仍然有测试覆盖率错误,例如,

如何在查看测试覆盖率时消除此错误。

编辑:

根据@Gérôme Grignon 的回答,如果我修改app.component.ts 文件但我不能 修改文件并且我只需要在app.component.spec.ts 文件中工作,那么任何人都可以建议像我上面提到的那样只处理 truthy 值的方法。

    clickHandler(value: string) {
      if (value) {
      }
    }

我已经尝试过,

expect(component.clickHandler('foo')).toBeTruthy();
expect(component.clickHandler('bar')).toBeFalsy();

但我得到了类似的错误,

预期为真不等于真。

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine angular8


    【解决方案1】:

    您在这里进行集成测试:您不测试功能,而是测试组件和模板之间的集成。

    这是一个测试你的功能的例子(添加一些随机逻辑):

    clickHandler(value: string) {
      if (value === 'foo') {
        return true;
      }
      return false;
    }
    
    it('should return value', () => {
    expect(component.clickHandler('foo')).toEqual(true);
    expect(component.clickHandler('bar')).not.toEqual(true);
    })
    

    【讨论】:

    • 感谢您的回答,如果只需要检查是否有价值而不是比较像if (value === 'foo'),我应该在这里做什么
    • 如果我给if(value) 那么它会抛出错误Expected true not to equal true. ..
    • 你能帮我检查一下值是真的而不是比较吗?如果这样做没关系..因为我应该不对component.ts文件进行任何更改..
    • 您能否提供有关您的用例的更多信息?这个函数的目标是什么?为什么不能修改组件文件?
    • 有人正在编写 ts 文件,因此我的任务是只为给定场景编写测试用例,而不是修改 component.ts 文件。..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2021-05-31
    • 2016-08-07
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多