Miomir Dancevic
Miomir Dancevic

Reputation: 6852

TypeError: Cannot set property 'formGroup' of undefined

I have some component like this

import { Component, Input } from '@angular/core';
import { WorkingHours } from '../../../../../hours';
import { FormGroup } from '@angular/forms';

@Component({
  selector: '[app-working-hours]',
  templateUrl: './working-hours.component.html',
  styleUrls: ['./working-hours.component.scss']
})

export class WorkingHoursComponent {
  @Input() properties: { formGroup: FormGroup; workingHours: WorkingHours; index: number; period: string; };
  get formControls(): any { return this.properties.formGroup.controls; }

  constructor() {
  }
}

and test like this

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';

import { WorkingHoursComponent } from './working-hours.component';
import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';

describe('WorkingHoursComponent', () => {
    let component: WorkingHoursComponent;
    let fixture: ComponentFixture<WorkingHoursComponent>;

    beforeEach(async(() => {
        imports.push(ReactiveFormsModule);

        TestBed.configureTestingModule({
            imports: imports,
            declarations: [
                WorkingHoursComponent
            ],
            schemas: [NO_ERRORS_SCHEMA]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(WorkingHoursComponent);
        component = fixture.componentInstance;
        let fixed = new FormControl(false);
        let startTime = new FormControl('');
        let endTime = new FormControl('');
        component.properties.formGroup = new FormGroup({
          fixed,
          startTime,
          endTime
        });
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

But I always get error TypeError: Cannot set property 'formGroup' of undefined Can somebody help me where I am wrong, thanks?

Upvotes: 2

Views: 982

Answers (1)

Hsuan Lee
Hsuan Lee

Reputation: 2330

Because the property has no default value, Try this.

component.properties.formGroup = {
  formGroup: new FormGroup({
    fixed,
    startTime,
    endTime
  }),
  index: 0,
  period: 'period'
}

Upvotes: 1

Related Questions