如何测试角度简单函数?

问题描述 投票:0回答:1

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

我尝试过的代码。

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功能。

为此,我已经尝试了上述方法,虽然成功了,但仍然遇到测试覆盖率错误,]

enter image description here

在查看测试范围时如何摆脱这个错误。

编辑:

基于@GérômeGrignon的回答,如果我修改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 angular8 angular-test
1个回答
0
投票

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

这里是一个示例,用于测试您的功能(添加一些随机逻辑):

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);
})
© www.soinside.com 2019 - 2024. All rights reserved.