首页 > 解决方案 > 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);
}

我究竟做错了什么

标签: angularjasmineangular-test

解决方案


你没有在你的期望声明中比较相同的东西。

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

像这样的东西甚至允许你使用间谍。


推荐阅读