Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 通过Jasmine中的@input模拟父FormGroup_Unit Testing_Karma Jasmine_Angular Reactive Forms_Formbuilder_Angular4 Forms - Fatal编程技术网

Unit testing 通过Jasmine中的@input模拟父FormGroup

Unit testing 通过Jasmine中的@input模拟父FormGroup,unit-testing,karma-jasmine,angular-reactive-forms,formbuilder,angular4-forms,Unit Testing,Karma Jasmine,Angular Reactive Forms,Formbuilder,Angular4 Forms,所以我有一个子组件,类似这样 export class ChildComponent implements OnInit { @Input('parentForm') public parentForm: FormGroup; constructor(private fb: FormBuilder, private cd: ChangeDetectorRef) { } ngOnInit() { this.parentForm.addControl('newContr

所以我有一个子组件,类似这样

export class ChildComponent implements OnInit {

  @Input('parentForm')
  public parentForm: FormGroup;

  constructor(private fb: FormBuilder, private cd: ChangeDetectorRef) { }

  ngOnInit() {
    this.parentForm.addControl('newControl', <Some Control>);
  }
}
导出类ChildComponent实现OnInit{
@输入('parentForm')
公共父窗体:FormGroup;
构造函数(私有fb:FormBuilder,私有cd:ChangeDetectorRef){}
恩戈尼尼特(){
this.parentForm.addControl('newControl',);
}
}
接下来我有一个基本的单元测试文件,它是这样的

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule],
      declarations: [ ChildComponent ],
      providers: [ FormBuilder, FormGroup ]
    })
    .compileComponents();
  }));

  beforeEach(inject([FormBuilder], (fb: FormBuilder) => {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    component.parentForm = fb.group({});
    component.ngOnInit();
    fixture.detectChanges();
  }));

  fit('should be created', () => {
    expect(component).toBeTruthy();
  });
});
description('ChildComponent',()=>{
let组件:子组件;
let夹具:组件夹具;
beforeach(异步(()=>{
TestBed.configureTestingModule({
导入:[ReactiveFormsModule,FormsModule],
声明:[ChildComponent],
提供者:[FormBuilder,FormGroup]
})
.compileComponents();
}));
每次之前(注入([FormBuilder],(fb:FormBuilder)=>{
fixture=TestBed.createComponent(ChildComponent);
组件=fixture.componentInstance;
component.parentForm=fb.group({});
组件。ngOnInit();
fixture.detectChanges();
}));
拟合('应创建',()=>{
expect(component.toBeTruthy();
});
});
以前我遇到了一个问题,父窗体没有定义,所以我试图通过在beforeach中注入FormBuilder来构建它,方法是执行以下操作:
component.parentForm=fb.group({})。然而现在的问题是因果报应/茉莉找不到FormBuilder

找不到名称“FormBuilder”。

当我在单元测试期间创建组件实例时,我尝试获取或模拟父窗体,我需要它,因为我在for each期间调用ngOnInit,将其作为一个新控件


任何想法。谢谢

我成功地为反应式表单父-子组件设置了Karma spec测试。希望下面的示例将有助于指导您的设置。我已经简化了代码库中的代码,将重点放在您试图解决的核心问题上

父组件 parent.component.html 子组件 child.component.html child.component.spec.ts
从'@angular/core/testing'导入{async,ComponentFixture,TestBed,inject};
从“@angular/core”导入{CUSTOM_ELEMENTS_SCHEMA}”;
从“@angular/forms”导入{FormsModule、ReactiveFormsModule、FormGroup、FormBuilder、Validators};
从“./child.component”导入{ChildFormComponent};
描述('ChildFormComponent',()=>{
let组件:ChildFormComponent;
let夹具:组件夹具;
beforeach(异步(()=>{
TestBed.configureTestingModule({
模式:[
自定义\u元素\u模式
],
进口:[
FormsModule,
反应窗体模块
],
声明:[
子窗体组件
]
})
.compileComponents();
}));
每次之前(注入([FormBuilder],(fb:FormBuilder)=>{
fixture=TestBed.createComponent(Step2Component);
组件=fixture.componentInstance;
/*这是我们可以模拟/测试组件的地方
并为formGroup传入一个值,否则它会
需要从家长那里得到它
*/
component.formGroup=fb.group({
名称:[“其他名称”,验证器。必需],
电子邮件:['',验证人。必填]
});
fixture.detectChanges();
}));
它('应该创建',()=>{
expect(component.toBeTruthy();
});
});

您是否能够解决此问题?我的情况也一样。但我收到“无法解析FormGroup:(?,?,?)的所有参数”错误。我注意到您的代码中有一个输入错误:
inject([FormBuidler],(fb:FormBuilder)
应该是:
inject([FormBuilder],(fb:FormBuilder)
这真是太棒了。谢谢!仅供参考,我在每次之前的第二个结尾处遗漏了第二个右括号…@JamesYoung感谢您让我知道,很高兴这对您有所帮助!:)虽然我不再做这种类型的编码了,但我还是很感激你的回答!希望我在遇到问题时能找到这个问题哈哈哈,很不幸我发现这个问题太晚了!希望它能在将来帮助其他人。我遇到了同样的问题,所以这让我解决了它,我学会了如何自己解决它。@Pixxl it只是帮助了我。非常感谢和来自未来的问候!
...
<div [stepControl]="childFormGroup">
  <child-form-group [formGroup]="childFormGroup"></child-form-group>
</div>
...
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'form-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss']
})
export class FormParentComponent implements OnInit {
  // childFormGroup will be available on the parent DOM
  // so we can inject it / pass it to the ChildFormComponent
  public childFormGroup : FormGroup;

  constructor(private _formBuilder: FormBuilder) {
    this.createForm();
  }

  private createForm() : void {
    this.childFormGroup = this._formBuilder.group({
      name:  ['Sample Name', Validators.required],
      email: ['', Validators.required]
    });
  }
}
...
<form [formGroup]="formGroup">
  <p>This is the childFormGroup</p>
  <br>

  <div>
    <input  placeholder="Name"
            formControlName="name"
            autocomplete="off">
  </div>

  <div>
    <input  placeholder="Email"
            formControlName="email"
            autocomplete="off">
  </div>
</form>
...
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'child-form-group',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],
})
export class ChildFormComponent {
  // This declares an inherited model available to this component
  @Input() formGroup : FormGroup;

  constructor() { }

  /* There is no need to create the formGroup here
     hence no constructor method call or ngOnInit() hook...
     It will simply inherit the formGroup by passing it as an
     attribute on the DOM from parent.component.html
  */
}
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';

import { ChildFormComponent } from './child.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA
      ],
      imports: [
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [
        ChildFormComponent
      ]
    })
    .compileComponents();
   }));

  beforeEach(inject([FormBuilder], (fb: FormBuilder) => {
    fixture = TestBed.createComponent(Step2Component);
    component = fixture.componentInstance;

    /* This is where we can simulate / test our component
       and pass in a value for formGroup where it would've otherwise
       required it from the parent
    */
    component.formGroup = fb.group({
      name:  ['Other Name', Validators.required],
      email: ['', Validators.required]
    });
    fixture.detectChanges();
  }));

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