【问题标题】:Angular Unit Test for passing FormGroup as @Input将 FormGroup 作为 @Input 传递的 Angular 单元测试
【发布时间】:2023-04-02 06:00:01
【问题描述】:

我想做一些单元测试,有一个 formGroup 作为输入从父组件传递到子组件,该怎么做。

app.componet.ts

        import { Component, Input } from '@angular/core';
        import { FormGroup, FormControl } from '@angular/forms';
        import { TranslateHelper } from '@app/core/translation';
        
        @Component({
            selector: 'basic-info',
            templateUrl: './'basic.component.html',
            styleUrls: ['./basic.component.scss']
        })
        export class BasicInfoComponent {
            @Input() form: FormGroup;
        
            constructor(private translation: TranslateHelper) {
        
            }
        
            get w(): FormControl {
                return this.form.get('y') as FormControl;
            }
        
            get x(): FormControl {
                return this.form.get('x') as FormControl;
            }
        
            get y(): FormControl {
                return this.form.get('y') as FormControl;
            }
        
            get z(): FormControl {
                return this.form.get('z') as FormControl;
            }
        
        }

app.component.spec.ts

       import { async, ComponentFixture, TestBed } from '@angular/core/testing';
       import { TranslateModule } from '@ngx-translate/core';
            
       import { BasicInfoComponent } from './kyc.component';
       import { FormGroup, FormsModule, ReactiveFormsModule, FormControl, FormBuilder } from '@angular/forms';
       import { TranslateHelper } from '@app/core/translation';
            
            describe('BasicInfoComponent', () => {
                let component: BasicInfoComponent;
                let fixture: ComponentFixture<BasicInfoComponent>;
                const fb = jasmine.createSpyObj('FormBuilder', ['group']);
                const formGroup = new FormGroup(
                    { identityVerificationDocumentTypeId: new FormControl('sfs'), addressVerificationDocumentTypeId: new FormControl('test!') });
                (<jasmine.Spy>(fb.group)).and.returnValue(formGroup);
            
                beforeEach(async(() => {
                    TestBed.configureTestingModule({
                        imports: [
                            ReactiveFormsModule,
                            FormsModule,
                            TranslateModule.forRoot()
                        ],
                        providers: [
                            TranslateHelper,
                            { provide: FormBuilder, useValue: fb }
                        ],
                        declarations: [BasicInfoComponent]
                    })
                        .compileComponents();
                }));
            
                beforeEach(() => {
                    fixture = TestBed.createComponent(BasicInfoComponent);
                    component = fixture.componentInstance;
                    fixture.detectChanges();
                });
            
                it('should create', () => {
                    expect(component).toBeTruthy();
                });
            
                describe('control getters', () => {
                    it('should return x control', () => {
                        const control = component.form.controls['x'];
                        expect(control).toBeTruthy();
                    });
            
                    it('should return y control', () => {
                        const control = component.form.controls['y'];
                        expect(control).toBeTruthy();
                    });
                });
            
            });

错误

Error: formGroup expects a FormGroup instance. Please pass one in.

       Example:

       
    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });
Error: formGroup expects a FormGroup instance. Please pass one in.

       Example:

       
    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });

【问题讨论】:

  • BasicInfoComponent 需要定义 form 属性才能正常工作。你在哪里设置的?嘲笑FormBuilder 对你没有任何作用

标签: angular angular-unit-test


【解决方案1】:

您需要创建一个formGroup 实例。

在您的规范文件 (app.component.spec.ts) 中,在 beforeEach 上添加以下内容

  beforeEach(() => {
    fixture = TestBed.createComponent(BasicInfoComponent);
    component = fixture.componentInstance;
    // The component expect an input called `form`. You have to supply it in the test
    component.form = new FormGroup({
      x: new FormControl('', Validators.required),
      y: new FormControl('', Validators.required),
      z: new FormControl('', Validators.required),
    });
    fixture.detectChanges();
  });

【讨论】:

  • 这是我的输入控制器,this.fb.group({ w: ['', Validators.required], xy: ['', Validators.required], y: ['', Validators .required], z: ['', Validators.required], });我应该在里面放什么componet.form
  • @ZahidRahman 这是你的组件export class BasicInfoComponent { @Input() form: FormGroup;必须设置component.form
  • @ZahidRahman 我已经添加了你需要设置的 sn-p component.form
  • @AhmadAlfy 它显示错误类型 '(string | ((control: AbstractControl) => ValidationErrors))[]' is missing the following properties from type 'AbstractControl': validator, asyncValidator, _parent, _asyncValidationSubscription , 和 44 上午
  • @ZahidRahman 您需要添加表单控件。我已经更新了答案
猜你喜欢
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-07
  • 1970-01-01
  • 2018-08-11
  • 2019-06-29
  • 1970-01-01
相关资源
最近更新 更多