我正在尝试通过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();
}));
测试结果是“预计间谍goHome被召唤”。有关如何使其工作的任何想法?
你应该使用fixture
和debugElement
而不是querySelector
it('should call goHome function', async(() => {
spyOn(component, 'goHome');
fixture.detectChanges();
let button = fixture.debugElement.queryAll(By.css('button')).nativeElement; // modify here
button.click();
fixture.detectChanges();
expect(component.goHome).toHaveBeenCalled();
}));