[英]Unit test a method called from a method
我有一个 angular 应用程序和一个在点击时被激怒的方法。 在这个方法中,我将一个值传递给另一个私有方法。
.ts 文件
public onViewItem(item: Results): void {
const ids = [item.data['id']];
this.anotherMethod(ids);
}
.spec 文件
it('should trigger a method on view item', () => {
component.onViewItem(documents[0]);
expect(component.onViewItem).toHaveBeenCalled();
});
我如何测试行const ids = [item.data['id']];
并检查this.anotherMethod(ids);
的调用this.anotherMethod(ids);
您必须监视要确保参数的方法。
spyOn(NameOfTheComponent, 'anotherMethod')
expect(NameOfTheComponent.anotherMethod).toHaveBeenCalledWith([IDEXPECTED])
有一个很好的做法:检查预期结果并避免检查在两者之间调用哪个方法。 这将使测试易于维护。
让我们用一个例子来探索它。
public onViewItem(item: Results): void {
const ids = [item.data['id']];
this.anotherMethod(ids);
}
public anotherMethod(ids: number[]): void {
this.ids = ids;
}
有哪些测试选项? 我看到两个:
坏的
anotherMethod
:
it('should trigger a method on view item', () => {
spyOn(NameOfTheComponent, 'anotherMethod')
component.onViewItem(documents[0]);
expect(component.anotherMethod).toHaveBeenCalledWith([documents[0].id]);
});
不错的
测试预期结果:
it('should trigger a method on view item', () => {
spyOn(NameOfTheComponent, 'anotherMethod')
component.onViewItem(documents[0]);
expect(component.ids).toEqual([documents[0].id]);
});
为什么好的更好? 考虑您重构了onViewItem
方法。 现在它看起来像这样:
public onViewItem(item: Results): void {
const ids = [item.data['id']];
this.ids = ids;
}
论据是一样的。 方法执行产生的结果也完全一样。 如果您对该功能进行了间谍活动,则您将被迫重构测试。 如果您刚刚测试了预期的结果 - 您很高兴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.