Ben Racicot
Ben Racicot

Reputation: 5980

How to use setValue and patchValue in testing angular 2 reactive forms

I can't seem to get the correct dependencies in my spec file for testing a new form I've created.

I have 2 passing tests but the 3rd comes to a hault when I use setValue or patchValue to setup my test form data.

Karma in browser gives: 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'}); 
    });

The question is: How do I use setValue/patchValue to setup my form object for a test form submission?

Upvotes: 2

Views: 13520

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209112

If you're using reactive forms, then you should have the FormGroup as a member of the component. This is what you need to access

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'}); 
});

Upvotes: 3

Related Questions