我有一个 plunkr ,并且在尝试遵循网络上的一些建议但没有成功之后,一直在尝试找出如何测试 EventEmitter。我想知道如何通过触发按钮的点击来测试它……更多的是组件测试。该代码位于 voter.component.ts 和 voter.componet.spec.ts 文件中。如有任何帮助,我们将不胜感激。
it('should emit on up/down vote click', fakeAsync((): void => {
let fixture: ComponentFixture = TestBed.createComponent(VoterComponent);
let instance: VoterComponent = fixture.componentInstance;
spyOn(instance.onVote, 'emit');
let button = findElement(fixture, 'button:first-child');
button.click();
fixture.detectChanges();
tick();
expect(instance.onVote.emit).toHaveBeenCalled(1);
}));
最佳答案
第一个观察是@Input 和@Output 装饰总是需要跟在一对括号之后,更多细节关于这个主题here .
您代码中的第二个问题是您在 onVote() 事件处理程序方法中递增 counter
而不是 this.counter
。
此外,作为旁注,不需要在父 (App) 组件的指令数组中声明 VoterComponent。
关于testing - Angular2 和测试 EventEmitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40699551/