angularjasminetestcase

How to write unit test case using Jamine to test form controls touched, untouched and dirty conditions


I have a form built using reactive forms angular and I have the below code. The entire if conditions says , branch not covered, how can i make sure the branch is covered.

this.tableOptions.rowData.forEach((element:any)=> {
   if(element.type.toLowerCase() == "payments") {
       if(((this.oldValue == this.myForm.controls['nameControl'].value) 
      || (this.myForm.controls['nameControl'].untouched)
|| (this.myForm.controls['nameControl'].touched && !this.myForm.controls['nameControl'].dirty))){

......
}

})

Solution

  • You have to mock the conditions so that the execution goes inside the if condition.

    Also note, I am failing all two if conditions, except the last, this is to demo a simple method to cover chained conditions with only one test case.

    it('should cover the code', () => {
        component.tableOptions = {
            rowData: [{type: "payments"}],
        } as any;
        component.oldValue = 'test';
        component.myForm = {
            controls: {
                nameControl: {
                    value: 'tester',
                    untouched: false,
                    touched: true,
                    dirty: false,
                }
            },
        } as any;
    });