角度单位测试按钮点击html

时间:2018-01-02 14:36:02

标签: angular karma-jasmine

我试图通过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();
  }));

测试结果是&#34; 预期的间谍goHome被调用。&#34; 有关如何使其发挥作用的任何想法?

1 个答案:

答案 0 :(得分:0)

您应该使用fixturedebugElement代替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();
  }));