Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Unit Testing Mat-Select

1: The mat-select has 4 values, 1,2,3,4.

The code below works good for the select. So I'd like to share if it helps the readers.

it('check the length of drop down', async () => {

    const trigger = fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement;
    trigger.click();
    fixture.detectChanges();
    await fixture.whenStable().then(() => {
        const inquiryOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
        expect(inquiryOptions.length).toEqual(4);
    });
});

2: I need another test to verify the default value in the same mat-select is 3 or not. When page loads the default value for the drop down is set to 3.

it('should validate the drop down value if it is set by default', async () => {

    const trigger = fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement;
    trigger.click();
    fixture.detectChanges();
    await fixture.whenStable().then(() => {
        const inquiryOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
        const value = trigger.options[0].value;
        expect(value).toContain(3);
    });
});

Any help is appreciated.

like image 888
Knight Avatar asked Sep 25 '18 19:09

Knight


2 Answers

let loader = TestbedHarnessEnvironment.loader(fixture);

const matSelect = await loader.getAllHarnesses(MatSelectHarness);
await matSelect[0].clickOptions();
const options = await matSelect[0].getOptions();
expect(await options[0].getText()).toMatch("");
expect(await options[1].getText()).toMatch('option1');
expect(await options[2].getText()).toMatch('option2');
like image 115
Jayamal Kulathunge Avatar answered Sep 19 '22 21:09

Jayamal Kulathunge


This one is worked for me in Angular 7

    const debugElement = fixture.debugElement;
    // open options dialog
    const matSelect = debugElement.query(By.css('.mat-select-trigger')).nativeElement;
    matSelect.click();
    fixture.detectChanges();
    // select the first option (use queryAll if you want to chose an option)
    const matOption = debugElement.query(By.css('.mat-option')).nativeElement;
    matOption.click();
    fixture.detectChanges();
    fixture.whenStable().then( () => {
       const inputElement: HTMLElement = debugElement.query(By.css('.ask-input')).nativeElement;
       expect(inputElement.innerHTML.length).toBeGreaterThan(0);
    });
like image 42
Günay Gültekin Avatar answered Sep 20 '22 21:09

Günay Gültekin