angular - Angular 单元测试功能
问题描述
我刚刚开始探索 Angular 的单元测试。我在 .ts 文件中有一个函数
onValueChange(val: number): void {
this.formGroup.get(this.controlName).setValue(val);
}
我正在尝试测试 controlName 是否具有在 onValueChange 参数中传递的值
我在 spec.ts 文件中试过这个
it('form value should update from form changes', fakeAsync(() => {
onValueChange(5);
expect(component.formGroup.get(component.controlName)).toEqual(5);
}));
function onValueChange(val: number): void {
component.formGroup.get(component.controlName).setValue(val);
}
我究竟做错了什么
解决方案
你没有在你的期望声明中比较相同的东西。
expect(component.formGroup.get(component.controlName).value).toEqual(5);
你错过了'.value'
除此之外,我认为您所做的在理论上不会算作测试原始 onValueChange 函数。我不确定您为什么在 .ts 文件而不是 .component.ts 文件中测试功能。如果您的功能包含在一个组件中,您可以轻松配置 TestBed 而无需在测试文件中重复该功能。
唉,如果你不能把它放在组件中,那么我不建议在测试文件中重新创建原始功能。在这种情况下(理想的解决方案是避免这种情况)有几个解决方法。
import myTestFunc from 'myFile.ts';
describe('Test function', () => {
let testObj;
beforeEach(()=>{
testObj = {myTestFunc: myTestFunc};
});
it('test', ()=>{
expect(testObj.myTestFunc()).toBe(something);
});
});
像这样的东西甚至允许你使用间谍。
推荐阅读
- c# - MVVM 与模型中的集合绑定
- rest - 访问后端地理数据库
- c - 如何一次读取所有 CPU 内核的频率?
- java - 如何从 Kafka Producer 返回具有数十亿条记录的 ArrayList?
- php - Wordpress - 如何将类别页面更改为完整列表视图?
- c# - 如何仅在 VSTO 应用程序之上制作 WPF 窗口?
- r - 将函数结果存储在 R 中的复杂对象 (?) 中
- python - Deep learning: Training set tends to be good and Validation set is bad
- c# - JSON数组到数组列表使用c#
- android - Android Navigation Architecture 组件,处理不同的 backstacks