【发布时间】:2018-06-12 06:28:42
【问题描述】:
我正在尝试通过 html 测试按钮事件组件调用。该按钮在手动运行时起作用。我可以直接成功测试组件。我也可以成功测试按钮渲染,但是通过html执行测试时没有看到函数调用。
HTML:
<div class="row">
<button id="homeBtn" class="btn btn-primary" [routerLink]="['home']">Home</button>
</div>
组件代码:
export class AppComponent {
title = 'My app';
constructor(private router: Router) {}
goHome() {
this.router.navigate(['./']);
}
测试规范:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
FormsModule,
RouterModule.forRoot(ROUTES),
RouterTestingModule.withRoutes([])
],
providers: [
{ provide: APP_BASE_HREF, useValue: '/' }
]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.debugElement.componentInstance;
instance = fixture.debugElement.nativeElement;
}));
// this test works
it('home button should work', () => {
spyOn(component, 'goHome');
component.goHome();
expect(component.goHome).toHaveBeenCalled();
});
// this test works
it('should render the HOME button', async(() => {
spyOn(component, 'goHome');
fixture.detectChanges();
let button = instance.querySelector('#homeBtn');
expect(button.textContent).toContain('Home', 'button renders');
}));
// this test fails
it('should call goHome function', async(() => {
spyOn(component, 'goHome');
fixture.detectChanges();
let button = instance.querySelector('#homeBtn');
button.click();
fixture.detectChanges();
expect(component.goHome).toHaveBeenCalled();
}));
测试结果是“预期 spy goHome 已被调用。” 关于如何让它发挥作用的任何想法?
【问题讨论】:
标签: angular karma-jasmine