单元测试 – 任何方式在Angular2中测试EventEmitter?

前端之家收集整理的这篇文章主要介绍了单元测试 – 任何方式在Angular2中测试EventEmitter?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用EventEmitter的组件,当单击页面上的某个人时使用EventEmitter.有什么办法可以在单元测试期间观察EventEmitter,并使用TestComponentBuilder单击触发EventEmitter.next()方法的元素,并查看发送的内容
您的测试可能是:
it('should emit on click',inject([],() => {
   tcb.createAsync(MyComponent)
      .then((fixture) => {
        // spy on event emitter
        let component = fixture.componentInstance; 
        spyOn(component.myEventEmitter,'emit');

        // trigger the click
        let nativeElement = fixture.nativeElement;
        let button = nativeElement.querySelector('button');
        button.dispatchEvent(new Event('click'));

        fixture.detectChanges();

        expect(component.myEventEmitter.emit).toHaveBeenCalledWith('hello');
      });
}));

当你的组件是:

@Component({ ... })
class MyComponent {
  @Output myEventEmitter = new EventEmitter();

  buttonClick() {
    this.myEventEmitter.emit('hello');
  }
}
原文链接:https://www.f2er.com/angularjs/140559.html

猜你在找的Angularjs相关文章