lundi 16 avril 2018

Angular test template driven form written in material

I'm trying to write a test for my Component. My Component has a form with a dropdown(mat-select) field in it with required attribute on it.

enter image description here

If I set a value in it, the form is valid:

enter image description here

How do I test this. I want to write a test that expects form.invalid to be truthy before I set the value and form.valid to be truthy after value has been set.

it('should validate the app', () => {
let fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    fixture.detectChanges();
    let component = fixture.componentInstance;
    expect(component.form.invalid).toBeTruthy();
    component.myobject.value = "ABC";
    expect(component.form.valid).toBeTruthy();

  });
});

If test looks like above the ngModel found on the form object representing my field is pretty much unchanged.

If I add fixture.detectChanges() (not sure when to call this method) after I set the value, the model of the field will be "ABC" but the value of the field is "":

it('should validate the app', () => {
let fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    fixture.detectChanges();
    let component = fixture.componentInstance;
    expect(component.form.invalid).toBeTruthy();
    component.myobject.value = "ABC";
    fixture.detectChanges();
    expect(component.form.valid).toBeTruthy();

  });
});

enter image description here

My feeling is that the mat-select field isn't properly initiated, it hasn't calculated what valid options there is yet. If I debug and inspect the dom there are no options drawn when setting the value.

Does anyone know how to solve this ?

I made a simple github repo if anyone wants to clone and try:

https://github.com/trashhead/angular-templ-drivn-form-test

Aucun commentaire:

Enregistrer un commentaire