Search code examples
angulartestingjasminekarma-jasmine

Test case about multiple mat-select and mat-option


it('should update control2 options when control1 is changed to "b"', (() => {
const control1Select = fixture.nativeElement.querySelector(
  'mat-select[formControlName="control1"]'
);
const control2Select = fixture.nativeElement.querySelector(
  'mat-select[formControlName="control2"]'
);

// Select "b" for control1
control1Select.value = 'b';
control1Select.dispatchEvent(new Event('change'));

fixture.detectChanges(); 

const control2Options = control2Select.querySelectorAll('mat-option');
expect(control2Options.length).toBe(3); // Expect 3 options when control1 is "b"
}));

I have tried many solution but it didn't work it out. when user selects an option from control1 then option for control2 will be decided using function in .ts file. Need to write the test case for this functionality.

I have also add fakeAsync and tick.

I also tried:

control1Select.value = 'b';
control1Select.dispatchEvent(new Event('change'));

I also tried:

fixture.whenStable().then(() => {
const control2Options = control2Select.querySelectorAll('mat-option');
expect(control2Options.length).toBe(3); // Expect 3 options when control1 is "b"
done();
});

Error: Expected 0 to be 3.


Solution

  • This is why in these scenarios, it may be more preferable to use reactive forms API because it may be difficult to get the JavaScript events and HTML right for the value to change.

    Something like this is difficult to do to see the update:

    control1Select.value = 'b';
    control1Select.dispatchEvent(new Event('change'));
    
    fixture.detectChanges();
    

    If I were you, I would directly change the form control from TypeScript.

    it('should update control2 options when control1 is changed to "b"', () => {
      // Select "b" for control1, use setValue
      component.form.get("control1").setValue("b");
    
      fixture.detectChanges(); 
    
      const control2Select = fixture.nativeElement.querySelector(
        'mat-select[formControlName="control2"]'
      );
      const control2Options = control2Select.querySelectorAll('mat-option');
      expect(control2Options.length).toBe(3); // Expect 3 options when control1 is "b"
    });