【发布时间】: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