2017-04-14 16 views
0

作成した新しいフォームをテストするためにspecファイルに正しい依存関係を取得できないようです。角度2反応性フォームのテストでsetValueとpatchValueを使用する方法

私は2回の合格テストを行っていますが、setValueまたはpatchValueを使用してテストフォームデータを設定すると、3回目は怖いことになります。ブラウザで

カルマができます:TypeError: Cannot read property 'patchValue' of undefined

import { TestBed, async } from '@angular/core/testing'; 
import { Component, ViewChild } from '@angular/core'; 
import { MyComponent } from './my.component'; 
import { NgForm, ReactiveFormsModule, FormGroup, FormControl, FormArray } from '@angular/forms'; 


describe('My component test: ',() => { 

    beforeEach(() => { 
     TestBed.configureTestingModule({ 
      declarations: [MyComponent], 
      imports: [ReactiveFormsModule], 
      providers: [] // which provider for setValue/patchValue? 
     }); 

     let fixture = TestBed.createComponent(MyComponent); 
     let myComponent = fixture.debugElement.componentInstance; 

    }); 


    it('sending form values to the service onSubmit method',() => { 
     // TypeError: Cannot read property 'patchValue' of undefined 
     this.jobForm.patchValue({'title': 'a spec title'}); 
    }); 

質問は:どのように私はのsetValue/patchValueセットアップ私のフォームオブジェクトには、テスト・フォーム送信のために使うのですか?

答えて

0

リアクティブフォームを使用している場合は、コンポーネントのメンバーとしてFormGroupが必要です。これは、あなたが

let component; 
let fixture; 

beforeEach(() => { 
    TestBed.configureTestingModule({ 
     declarations: [MyComponent], 
     imports: [ReactiveFormsModule], 
     providers: [] // which provider for setValue/patchValue? 
    }); 

    fixture = TestBed.createComponent(MyComponent); 
    component = fixture.debugElement.componentInstance; 
    fixture.detectChanges() 
}); 


it('sending form values to the service onSubmit method',() => { 
    // assuming the property on the component is named jobForm 
    const form = component.jobForm; 

    form.patchValue({'title': 'a spec title'}); 
}); 
+0

はい、私が持っている、とあなたは私はあなたが 'form'のconstを追加しましたように見えますが、その後、あなたがそれを使用していない –

+0

やっているやっていないにアクセスするために必要なものです。それは私が見るものです。私は何が欠けていますか? – BenRacicot

+0

編集を参照してください.... –

関連する問題