[英]How do I test loaded data into a reactive form with Jasmine in Angular 6?
我有一個Angular 6應用程序,它使用ngrx將數據從存儲對象加載到反應形式中 。 我正在嘗試對此進行單元測試,但是無論我進行什么更改,似乎我分配的表單對象始終具有空白值。
這是我的代碼:
HTML
<form [formGroup]="myForm" novalidate>
<input id="name" formControlName="name" />
<input id="age" formControlName="age" />
</form>
零件
export interface MyObject {
name: string;
age: string;
}
export class MyObjectComponent {
myObject: MyObject;
myForm: FormGroup;
constructor(private fb: FormBuilder, private store: Store<fromStore.State>) { }
ngOnInit() {
this.myForm = this.fb.group({
name: [null, [Validators.required]],
age: [null, [Validators.required]]
});
this.store.select(fromStore.getMyObject).subscribe(x => this.myForm.patchValue(x));
}
規格文件
describe('MyObjectComponent', () => {
let component: MyObjectComponent;
let fixture: ComponentFixture<MyObjectComponent>;
let store: Store<fromStore.State>;
let initialStateL MyObject;
let el: DebugElement;
beforeEach(async(() => {
initialState = {
name: 'My Name',
age: 55
};
TestBed.configureTestingModule({
imports: [
FormsModule,
ReactiveFormsModule,
HttpClientModule,
StoreModule.forRoot({}),
StoreModule.forFeature('my-object', reducer)
],
declarations: [MyObjectComponent],
providers: []
})
.compileComponents().then(() => {
fixture = TestBed.createComponent(MyObjectComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
spyOn(store, 'dispatch').and.callThrough();
fixture.detectChanges();
});
}));
it('should patch values into form', async(() => {
expect(component.myForm.controls.age.value).toBe(55);
}
}
測試總是無法說出表單中的值是空。 有人知道我在做什么錯嗎? 謝謝!
這是詳細的分配:
首先為表單創建模擬值,訪問表單並分配值,然后需要觸發組件上的更改檢測,最后測試輸入的值。
我尚未測試此代碼,但我認為您要嘗試執行的操作確實很接近。
describe('MyObjectComponent', () => {
// Rest of code...
it('should patch values into form', async(() => {
// Mock value
const mock_age_value = 55;
fixture = TestBed.createComponent(DualityAccordionTabComponent);
const compiled = fixture.componentInstance;
// Value assignation
compiled.myForm.patchValue({
age: mock_age_value
});
// Trigger change detection
fixture.detectChanges();
expect(component.myForm.controls.age.value).toBe(55);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.