Search code examples
angularunit-testingjasminekarma-jasmine

How can i test this function in Angular 2


moveColumns(shifter: number, index: number) {
    const columnFields = this.form.get('sizes') as FormArray;
 
    let newIndex = index + shifter;
    if (newIndex === -1) {
      newIndex = columnFields.length - 1;
    } else if (newIndex === columnFields.length) {
      newIndex = 0;
    }
 
    const currentGroup = columnFields.at(index);
    columnFields.removeAt(index);
    columnFields.insert(newIndex, currentGroup);
  }

My dificculty is that they are all inside function variables and not component global variables.


Solution

  • You need to stub the form object and then validate the changes that happen in the function

    // in your test beforeEach
    mockComponent.form = new FormArray({sizes: new FormControl());
    
    // And in your function, you can update this form object and validate it
    
    it('should test my function', () => {
    const modifiedForm = {} // Add the final result after the function executes
    
    expect(mockComponent.form).toEquals(modifiedForm);
    })