Angular中的单元测试点击事件

新手上路,请多包涵

我正在尝试将单元测试添加到我的 Angular 2 应用程序中。在我的一个组件中,有一个带有 (click) 处理程序的按钮。当用户单击按钮时,调用在 .ts 类文件中定义的函数。该函数在 console.log 窗口中打印一条消息,说明该按钮已被按下。我当前的测试代码测试打印 console.log 消息:

 describe('Component: ComponentToBeTested', () => {
    var component: ComponentToBeTested;

    beforeEach(() => {
        component = new ComponentToBeTested();
        spyOn(console, 'log');
    });

    it('should call onEditButtonClick() and print console.log', () => {
        component.onEditButtonClick();
        expect(console.log).toHaveBeenCalledWith('Edit button has been clicked!);
    });
});

但是,这仅测试控制器类,而不是 HTML。我不只是想测试在调用 onEditButtonClick 时发生日志记录;我还想测试当用户单击组件的 HTML 文件中定义的编辑按钮时调用 onEditButtonClick 。我怎样才能做到这一点?

原文由 Aiguo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 592
2 个回答

我的目标是检查用户单击编辑按钮时是否调用了“onEditButtonClick”,而不是仅检查正在打印的console.log。

您需要首先使用 Angular TestBed 设置测试。这样,您实际上可以抓住按钮并单击它。你要做的是配置一个模块,就像你配置一个 @NgModule ,只是为了测试环境

import { TestBed, async, ComponentFixture } from '@angular/core/testing';

describe('', () => {
  let fixture: ComponentFixture<TestComponent>;
  let component: TestComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ],
      declarations: [ TestComponent ],
      providers: [  ]
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(TestComponent);
      component = fixture.componentInstance;
    });
  }));
});

然后你需要窥探 onEditButtonClick 方法,点击按钮,检查该方法是否被调用

it('should', async(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click();

  fixture.whenStable().then(() => {
    expect(component.onEditButtonClick).toHaveBeenCalled();
  });
}));

这里我们需要运行一个 async 测试,因为按钮点击包含异步事件处理,需要通过调用 fixture.whenStable() 等待事件处理

更新

现在首选使用 fakeAsync/tick 组合,而不是 async/whenStable 组合。如果进行了 XHR 调用,则应使用后者,因为 fakeAsync 不支持它。所以不是上面的代码,重构,它看起来像

it('should', fakeAsync(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click();
  tick();
  expect(component.onEditButtonClick).toHaveBeenCalled();

}));

不要忘记导入 fakeAsynctick

也可以看看:

原文由 Paul Samsotha 发布,翻译遵循 CC BY-SA 4.0 许可协议

要首先检查按钮调用事件,我们需要监视将在按钮单击后调用的方法,因此我们的第一行将是 spyOn spy 方法,带有两个参数 1)组件名称 2)要监视的方法,即:’onSubmit’ 记住不要使用’ ()’ 只需要名称然后我们需要使按钮对象被点击现在我们必须触发事件处理程序,我们将在该事件处理程序上添加点击事件然后我们希望我们的代码调用一次提交方法

it('should call onSubmit method',() => {
    spyOn(component, 'onSubmit');
    let submitButton: DebugElement =
    fixture.debugElement.query(By.css('button[type=submit]'));
    fixture.detectChanges();
    submitButton.triggerEventHandler('click',null);
    fixture.detectChanges();
    expect(component.onSubmit).toHaveBeenCalledTimes(1);
});

原文由 Afzal Azad 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进