【问题标题】:TypeError: Cannot set property 'formGroup' of undefinedTypeError:无法设置未定义的属性“formGroup”
【发布时间】:2019-12-26 08:01:04
【问题描述】:

我有一些这样的组件

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() {
  }
}

并且像这样测试

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

但我总是出错 TypeError:无法设置未定义的属性“formGroup” 有人可以帮我解决我的错误吗,谢谢?

【问题讨论】:

    标签: angular typescript unit-testing jasmine


    【解决方案1】:

    因为属性没有默认值,试试这个。

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

    【讨论】:

      猜你喜欢
      • 2015-09-09
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-20
      • 1970-01-01
      • 2022-08-16
      相关资源
      最近更新 更多