Angular 单元测试功能

Angular unit testing functions

我刚刚开始探索 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 语句中比较相同的东西。

expect(component.formGroup.get(component.controlName).value).toEqual(5);

您错过了“.value”

除此之外,我认为您所做的在理论上不会算作对原始 onValueChange 函数的测试。我不确定为什么你在 .ts 文件而不是 .component.ts 文件中有被测函数。 如果您的功能包装在一个组件中,您可以轻松配置 TestBed,而无需在测试文件中重复功能。
las,如果您不能将它放入组件中,那么我不建议在测试文件中重新创建原始功能。在这种情况下(理想的解决方案是避免这种情况)有几个解决方法。

import myTestFunc from 'myFile.ts';
describe('Test function', () => {
    let testObj;
    beforeEach(()=>{
        testObj = {myTestFunc: myTestFunc};
    });
    it('test', ()=>{
        expect(testObj.myTestFunc()).toBe(something);
    });
});

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