首页 > 解决方案 > Angular 6 - 单元测试 Mat-Select

问题描述

1:mat-select 有 4 个值,1,2,3,4。

下面的代码适用于选择。所以如果对读者有帮助,我想分享一下。

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:我需要另一个测试来验证同一个 mat-select 中的默认值是否为 3。当页面加载时,下拉菜单的默认值设置为 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);
    });
});

任何帮助表示赞赏。

标签: unit-testingkarma-jasmineangular6

解决方案


这个在 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);
    });

推荐阅读