加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – 通过Jasmine中的@input模拟父FormGroup

发布时间:2020-12-17 17:37:04 所属栏目:安全 来源:网络整理
导读:所以我有一个像这样的子组件 export class ChildComponent implements OnInit { @Input('parentForm') public parentForm: FormGroup; constructor(private fb: FormBuilder,private cd: ChangeDetectorRef) { } ngOnInit() { this.parentForm.addControl('n
所以我有一个像这样的子组件

export class ChildComponent implements OnInit {

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

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

  ngOnInit() {
    this.parentForm.addControl('newControl',<Some Control>);
  }
}

接下来我有一个这样的准系统单元测试文件

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

以前我有一个问题,其中parentForm未定义,因此我尝试通过在beforeEach中通过执行此component.parentForm = fb.group({});来注入FormBuilder来自己构建它.但是现在的问题是karma / jasmine无法找到FormBuilder

找不到名字’FormBuilder’.

我想要做的就是尝试获取或模拟parentForm,因为我在单元测试期间创建组件的实例时,我需要它,因为我在for each期间调用ngOnInit作为新控件.

有任何想法吗.谢谢

解决方法

我能够为Reactive Form Parent< - >设置成功的Karma规范测试.儿童组件.希望以下示例有助于指导您的设置.我已经从代码库中简化了尽可能多的代码,专注于您尝试解决的核心问题.

父组件

parent.component.html

...
<div [stepControl]="childFormGroup">
  <child-form-group [formGroup]="childFormGroup"></child-form-group>
</div>
...

parent.component.ts

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

子组件

child.component.html

...
<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>
...

child.component.ts

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
  */
}

child.component.spec.ts

import { async,ComponentFixture,TestBed,inject } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule,ReactiveFormsModule,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]
    });
    fixture.detectChanges();
  }));

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读