【发布时间】:2019-02-05 16:38:20
【问题描述】:
我正在为我的 Angular 6 项目编写单元测试。 但是,我遇到了一个问题。我想测试一个调用 click 函数的按钮,但测试文件总是显示这个错误。
以下是我的代码:
HTML:
<div>
<button (click)="onButtonClick(1)"><button>
<button (click)="onButtonClick(2)"><button>
<button (click)="onButtonClick(3)"><button>
</div>
comp.ts:
onButtonClick(key: number) {
do something
}
spec.ts
import { async, ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
import { PanelButtonsComponent } from './panel-buttons.component';
import { By } from "@angular/platform-browser";
describe('PanelButtonsComponent', () => {
let component: PanelButtonsComponent;
let fixture: ComponentFixture<PanelButtonsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [PanelButtonsComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PanelButtonsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it("should call onButtonClick ", fakeAsync(() => {
const onClickMock = spyOn(component, 'onButtonClick');
fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
expect(onClickMock).toHaveBeenCalled();
}));
});
测试结果:
预期的间谍 onButtonClick 已被调用。
有什么更正的建议吗?谢谢
更新
我已经推荐了另一个article,并按照代码:
it('should', async(() => {
spyOn(component, 'onButtonClick');
let button =
fixture.debugElement.nativeElement.querySelector('button');
button.click();
fixture.whenStable().then(() => {
expect(component.onButtonClick).toHaveBeenCalled();
})
}));
测试用例也不能通过。
更新 2:
在我的html中,有两种点击函数会被调用,所以会报错
<div>
<button (click)="onButtonClick(1)"><button>
<button (click)="onButtonClick(2)"><button>
<button (click)="onButtonClick(3)"><button>
<button (click)="onResetClick()"><button>
</div>
【问题讨论】:
-
你能把
fakeAsync改成async吗? -
好吧,问题是您在点击后没有 tick() 调用 :) 如果您使用
async()而不是fakeSync(),则没有必要这样做 -
我在那篇文章中尝试了另一个 async() 解决方案,但仍然无法正常工作
标签: angular typescript unit-testing jasmine karma-jasmine