I want to do a few unit tests there is a formGroup
passing as input from parent component to a child component, how to do it.
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
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
requiresform
property to be defined in order to work properly. Where did you set it? MockingFormBuilder
does nothing in your case – Huntsman