如何在测试角度2反应形式时使用setValue和patchValue

时间:2017-04-14 19:07:10

标签: forms unit-testing angular testing angular2-forms

我似乎无法在我的spec文件中获得正确的依赖项来测试我创建的新表单。

我有2次通过测试,但是当我使用setValue或patchValue设置我的测试表单数据时,第3次出现了问题。

浏览器中的Karma提供: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为测试表单提交设置表单对象?

1 个答案:

答案 0 :(得分:2)

如果您正在使用被动表单,那么您应该将Data.Typeable作为组件的成员。这是您需要访问的内容

FormGroup