Search code examples
javascriptangularunit-testing

Setting initial values to Angular form group for testing


I'm writing a unit test for an Angular 7 reactive form that has its input values pre-filled with server data on ngInit. How can I set the values of this form so that it doesn't five me a "value undefined" error during testing?

This is my form being pre-filled on ngOnInit:

 ngOnInit() {
  this.userForm = this.formBuilder.group({
  id: [ this.user.id ],
  first_name: [this.user.first_name, Validators.required],
  last_name: [this.user.last_name, Validators.required],
});

This is the current (barebones) test code for the form:

//import modules

describe('UserListItemComponent', () => {
  let component: UserListItemComponent;
  let fixture: ComponentFixture<UserListItemComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
    imports: [
      MaterialModule,
      ReactiveFormsModule,
      FormsModule,
    ],
    declarations: [
      UserListItemComponent,
    ],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
  })
  .compileComponents();
  }));

beforeEach(() => {
  fixture = TestBed.createComponent(UserListItemComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('should create', () => {
  component.userForm.setValue({
    id: 123,
    first_name: "john",
    last_name: "smith",
  });
  expect(component).toBeTruthy();
  });
});

However, the Karma test runner still says it's undefined for id. Is it because it's not pre-filling the data with setValue?


Solution

  • Calling fixture.detectChanges(); will call ngOnInit(), but the user property is undefined. You can change your code like this:

    fixture = TestBed.createComponent(UserListItemComponent);
    component = fixture.componentInstance;
    const user = {
    //your properties here
    };
    component.user = user;
    fixture.detectChanges();