简体   繁体   English

如何对 Angular 中的按钮单击事件进行单元测试?

[英]How to unit test a button click event in Angular?

I am trying to test a button click event.我正在尝试测试按钮单击事件。 The official Angular manual says there are two ways to do this.官方 Angular 手册说有两种方法可以做到这一点。

1. 1.

it('should raise selected event when clicked (triggerEventHandler)', () => {
  let selectedHero: Hero;
  const heroDe = fixture.debugElement.query(By.css('dashboard-hero'));
  comp.selected.subscribe((hero: Hero) => selectedHero = hero);
  heroDe.triggerEventHandler('click', null);
  expect(selectedHero).toBe(expectedHero);
});
it('should raise selected event when clicked (element.click)', () => {
  let selectedHero: Hero;
  const heroEl: HTMLElement = fixture.nativeElement.querySelector('.hero');
  comp.selected.subscribe((hero: Hero) => selectedHero = hero);
  heroEl.click();
  expect(selectedHero).toBe(expectedHero);
});

The first method worked well for me.第一种方法对我来说效果很好。 But when I tried the second option, the test ran without errors, but Karma started running tests in an infinite loop.但是当我尝试第二个选项时,测试运行没有错误,但 Karma 开始在无限循环中运行测试。

在此处输入图像描述

Here is my implementation of both ways.这是我对这两种方式的实现。

it('test1', () => {
  fixture.detectChanges();
  let treeNodeElement = fixture.debugElement.query(By.css('#buttonSend'));
  treeNodeElement.triggerEventHandler('click', null);
  expect(component.tabService.tabs.length).toBe(1);
  expect(component.tabService.tabs[0].title).toBe('Test1');
});

it('test2', () => {
  fixture.detectChanges();
  const treeNodeElement: HTMLElement = fixture.nativeElement.querySelector('#buttonSend');
  treeNodeElement.click();
  expect(component.tabService.tabs.length).toBe(1);
  expect(component.tabService.tabs[0].title).toBe('Test1');
});

Can you please tell me where is the error in the second option?你能告诉我第二个选项的错误在哪里吗?

The solution here for me was importing FormsModule and ReactiveFormsModule in beforeEach().我的解决方案是在 beforeEach() 中导入FormsModuleReactiveFormsModule The problem was that clicking on the button ( Which was a submit button ) engendred a browser behaviour which is refreshing the page.问题是单击按钮(这是一个提交按钮)会产生刷新页面的浏览器行为。 Even if the FormsModule and ReactiveFormsModule are imported in the component where the form is created, they have also to be imported in the.spec file where you are running the test case即使 FormsModule 和 ReactiveFormsModule 被导入到创建表单的组件中,它们也必须被导入到运行测试用例的 .spec 文件中

beforeEach(async () => {
 await TestBed.configureTestingModule({
  imports: [
    RouterTestingModule,
    RouterModule.forRoot([]),
    NgbModule,
    FormsModule,  <----
    ReactiveFormsModule,  <----
  ],
  declarations: [  
   ...

both module should be imported from @angular/forms两个模块都应该从 @angular/forms 导入

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM