我有一个使用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'); } }