Karma formGroup需要一个FormGroup实例。请通过一个

时间:2018-02-07 17:55:19

标签: angular jasmine tdd karma-jasmine

我理解错误的根源,我正在测试的组件需要将FormGroup传递给它@Input() form: FormGroup。在测试这个组件时,我无法弄清楚如何传递一个。

当我调用fixture.detectChanges()时,在我的每个函数之前出现错误,因此必须在该点之前传入表单

我当前的代码获取错误组未定义:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {
    ReactiveFormsModule,
    FormsModule,
    Validators,
    FormBuilder
} from '@angular/forms';
import { StaticComponent } from '../../firewall/static/static.component';

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

    beforeEach(
        async(() => {
            TestBed.configureTestingModule({
                declarations: [
                    StaticComponent
                ],
                imports: [
                    CommonModule,
                    ReactiveFormsModule,
                    FormsModule
                ],
                providers: [
                    NetworkService,
                    NetworkValidator,
                    HostNameValidator,
                    NotificationsService
                ]
            }).compileComponents();
        })
    );

    beforeEach(() => {
        fixture = TestBed.createComponent(StaticComponent);
        component = fixture.componentInstance;
        component.ruleForm = FormBuilder.group({
            chain: ['chain', Validators.required],
            ip: [
                '',
                Validators.required,
                this.networkValidator.validateNetwork('ip')
            ],
            action: ['action', Validators.required]
        });
        fixture.detectChanges();
    });

    fit('should be created', () => {
        expect(component).toBeTruthy();
    });
});

如何在测试期间将预制表单传递给组件的@Input?我似乎无法正确提供FormBuilder

2 个答案:

答案 0 :(得分:11)

这是我为您提出的测试组件规范。请注意我添加的模拟FormBuilder以及我在规范中提供它的方式。

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TestingComponent } from './testing.component';
import { FormBuilder, Validators } from '@angular/forms';

describe('TestingComponent', () => {
  let component: TestingComponent;
  let fixture: ComponentFixture<TestingComponent>;
  const formBuilder: FormBuilder = new FormBuilder();

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ TestingComponent ],
      providers: [ { provide: FormBuilder, useValue: formBuilder } ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestingComponent);
    component = fixture.componentInstance;
    component.ruleForm = formBuilder.group({
      chain: ['chain', Validators.required],
            ip: [
                '',
                Validators.required
            ],
            action: ['action', Validators.required]
    });
    fixture.detectChanges();
  });

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

这是我的测试组件,以防您需要参考。

import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-testing',
  templateUrl: './testing.component.html',
  styleUrls: ['./testing.component.css']
})
export class TestingComponent implements OnInit {
  ruleForm: FormGroup = new FormGroup({});
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.ruleForm = this.formBuilder.group({
      chain: ['chain', Validators.required],
            ip: [
                '',
                Validators.required
            ],
            action: ['action', Validators.required]
    });
  }
}

答案 1 :(得分:0)

运行detectChanges后,我遇到了相同的错误。但是,我组件的FormGroup是在ngOnInit中启动的,没有作为输入传递。

我的解决方案是将component under test包装在包装器组件中。此过程将迫使Angular将component under test置于生命周期事件中,例如ngOnInit,否则您将不得不调用自己。这也感觉像是使用输入来测试组件的正确方法。样板要多一些,但是这种方法更接近于模拟了angular的自然行为。

这里是此Medium article

的代码的复制件
  describe('ComponentUnderTestComponent', () => {
    let testHostComponent: TestHostComponent;
    let testHostFixture: ComponentFixture<TestHostComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ComponentUnderTestComponent, TestHostComponent]
    }).compileComponents();
    }));

    beforeEach(() => {
    testHostFixture = TestBed.createComponent(TestHostComponent);
    testHostComponent = testHostFixture.componentInstance;
    testHostFixture.detectChanges();
  });

  it('should show TEST INPUT', () => {
     expect(testHostFixture.nativeElement.querySelector('div').innerText)
         .toEqual('TEST INPUT');
  });

  @Component({
    selector: `host-component`,
    template: `<component-under-test input="test input"></component-under-test>`
  })
  class TestHostComponent {
  }
});