简体   繁体   中英

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 ?

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();

You can have a function to update the form values, when testing:

function updateForm(id: string, first_name: string, last_name: string) {
        component.userForm.controls['id'].setValue(id);
        component.userForm.controls['first_name'].setValue(first_name);
        component.userForm.controls['last_name'].setValue(last_name);
    }

In the test case:

 it('should create form', () => {
  updateForm('1','john','smith');
  expect(component).toBeTruthy();
  expect(component.userForm.value).toBeTruthy();
});

Or you can pass the user object to component using:

`component.user = mockUser;`

And the form values will be set onInit.

Most likely the error you have because of undefined user property on component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM