Search code examples
angularjasmineangular-test

Angular unit testing functions


I have just started exploring unit testing in angular. I have a function in .ts file

onValueChange(val: number): void {
this.formGroup.get(this.controlName).setValue(val);
}

I am trying to test if the controlName has the value passed in the onValueChange parameters

I tried this in the spec.ts file

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

what am I doing wrong


Solution

  • You are not comparing same things in your expect statement.

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

    You missed '.value'

    Apart from this, I don't think what you are doing will count as testing the original onValueChange function in theory. I am not sure why you have the function under test inside a .ts file rather than a .component.ts file. If your functionality is wrapped in a component, you can easily configure the TestBed and don't need to repeat the functionality in test file.
    Alas, if you can't put it inside a component even then I wouldn't recommend recreating the original functionality inside the test file. In such scenarios(ideal solution would be to avoid such scenarios) there are a couple of workarounds.

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

    Something like this even allows you to use spies.