Home > database >  Unit testing MatSelectChange with if else
Unit testing MatSelectChange with if else

Time:01-22

I am writing unit tests and I have this simple method that does something depending on the value of matSelectChange. How can I test this so the code coverage is 100%?

 selectionChanged(matSelectChange: MatSelectChange): void {
            if (matSelectChange.value === '1') {
                this.service.doSomething();
            } else if (matSelectChange.value === '2') {
                this.service.doSomethingElse();
            }
        }

CodePudding user response:

I would write the test like

describe('mat-select behaviour', () => {
  it('sould call doSomething if value is "1"', () => {
     const service = TestBed.inject(ServiceClass)
     spyOn(service, 'doSomething')
     const matSelect = fixture.debugElement.query(By.css('mat-select'))
     matSelect.triggerEventHandler('selectionChange', {value: '1'});
     fixture.detectChanges()
     expect(service.doSomething).toHaveBeenCalledWith('1');
  });
 it('sould call doSomething if value is "2"', () => {
     const service = TestBed.inject(ServiceClass)
     spyOn(service, 'doSomethingElse')
     const matSelect = fixture.debugElement.query(By.css('mat-select'))
     matSelect.triggerEventHandler('selectionChange', {value: '2'});
     fixture.detectChanges()
     expect(service.doSomethingElse).toHaveBeenCalledWith('2');
  });
})

before you can use the service class you must provide it in test setup

providers: [
   ServiceClass
]
  •  Tags:  
  • Related