1
votes

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

2

2 Answers

2
votes

I have found a way that seems to work now. I just don't understand what happens when running whenStable.

it('This one works', (done) => {
  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();
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(component.form.valid).toBe(true);
      done();
    })
  });
});

So the solution is that, after setting the dropdown value I have to do another whenStable and in that one check the validity of the form.

0
votes

have yout tried with:

expect(component.form.invalid).toBe(true) and next expect(component.form.valid).toBe(true) ?