2017-04-14 20 views
0

我似乎無法在我的spec文件中獲得正確的依賴項,以測試我創建的新窗體。如何在測試角2反應形式中使用setValue和patchValue

我有2個通過測試,但第三個來到時,我用setValue或patchValue來設置我的測試表單數據。

噶在瀏覽器提供: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

是的,我有什麼,你是不是做我在做什麼 –

+0

看起來你已經添加了一個'form'常量但你不使用它。這是我看到的差異。我錯過了什麼? – BenRacicot

+0

請參閱編輯.... –