这是应用程序组件中非常简单的功能,需要为其编写测试用例。
我尝试过的代码。
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ômeGrignon的回答,如果我修改app.component.ts
文件但我无法修改文件,则一切正常,我只需要在app.component.spec.ts
文件中工作,并且因此,任何人都可以像我上面提到的那样建议仅处理真实值的方法。
clickHandler(value: string) {
if (value) {
}
}
我尝试过的
expect(component.clickHandler('foo')).toBeTruthy();
expect(component.clickHandler('bar')).toBeFalsy();
但是我收到类似的错误
期望的true不等于true。
答案 0 :(得分: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);
})