【问题标题】:angular unit test button click through html角度单元测试按钮点击html
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 修改后的“按钮”变量返回为“未定义”。实例的初始使用在 beforeEach 中定义为instance = fixture.debugElement.nativeElement;。我还是新手,所以我不清楚其中的区别。
    • fyi.. 当我使用原始代码 console.log(button) 时,它返回:&lt;button _ngcontent-c15="" class="btn btn-primary" id="homeBtn" tabindex="0" ng-reflect-router-link="home"&gt;Home&lt;/button&gt; 之前使用相同定义的“按钮”测试验证按钮呈现。令人困惑的是测试未能调用 goHome 函数或识别它已被调用。
    • .queryAll() 返回一个数组。上面的代码不起作用!
    • 他对使用 debugElement 而不是 querySelector 进行平台无关测试是正确的。但是,是的,调用单击数组是不正确的。寻找相同的东西,测试元素是否可点击。
    • .queryAll() 应该是.query()
    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 2022-01-12
    相关资源
    最近更新 更多