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);
    });
});

这样的东西甚至可以让你使用间谍。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...