假设我有一个像这样的简单组件:
@Component({
selector: 'my-test',
template: '<div></div>'
})
export class test {
@Output selected: EventEmitter<string> = new EventEmitter<string>();
public onSelect(event: any) {
this.selected.emit(event.data);
}
}
测试它的最佳方法是什么?我见过这样的订阅:
it('should emit the selected item', (done) => {
myTest.selected.subscribe((result) => {
expect(result).toBe('123');
done();
}
//Act
myTest.onSelect({data:'123'});
}
或者像这样的 spy :
it('should emit the selected item', () => {
spyOn(myTest.selected, 'emit');
//Act
myTest.onSelect({data:'123'});
//Assert
expect(myTest.selected.emit).toHaveBeenCalledWith('123');
}
这两个构造通过了测试。我认为第二个更简单,所以我的问题是:这两个结构是否等效?是否有理由更好地使用第一个测试而不是第二个?为什么?
感谢您的宝贵时间。
最佳答案
他们以不同的方式测试同一件事。
我同意你的第二种形式更容易阅读,因为
- AAA 语法从上到下流动,而不是在回调内部流动
- 您正在测试直接效果(调用
emit
)
这与测试代码中不可见的间接效果(调用 subscribe
)形成对比。
关于javascript - 测试 eventEmiters 的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49095895/