用于将 FormGroup 作为 @Input 传递的 Angular 单元测试

标签 angular angular-unit-test

我想做几个单元测试有一个formGroup作为输入从父组件传递给子组件,如何做。
应用程序组件.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()
    });

最佳答案

您需要创建一个 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();
  });

关于用于将 FormGroup 作为 @Input 传递的 Angular 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63152757/

相关文章:

angular - 组件中的变量仅在 Angular 4 服务中的第二次函数调用后才会更新

angular - "An error was thrown in afterAll\n[object ErrorEvent] thrown"- Angular 4 单元测试

angular - Angular 4 单元测试 detectChanges() 中未调用 ngOnChanges

javascript - Angular 单元测试 : How to unit test . map()?

html - 带跨度的 PrimeNG 下拉菜单

Angular 在组件使用中包含 CDN

angular - 启动时的选项卡菜单

javascript - 我们如何在没有直接 @Output 的情况下检测 Angular2 中是否运行了更改检测?

angular - ng-bullet vs karma-parallel vs 在所有之前配置测试模块 - Angular 单元测试性能改进

angular - ng测试在 Angular 通用错误 "Incomplete: No specs found, , randomized with seed 48751"中失败