角度6 - 单位测试垫选择

问题描述 投票:3回答:2

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-testing karma-jasmine angular6
2个回答
2
投票

经过一些测试后,我找到了答案(至少对我的代码而言)并希望,这对你也有帮助:

当我查看DOM时,当应用程序运行时,我注意到mat-select的默认值在这个DOM结构中:

<mat-select>
    <div class="mat-select-trigger">
        <div class="mat-select-value">
            <span class="something">
                <span class="something">
                The value is here!

但在我的情况下,我在.ts文件中有一个表单生成器,它在ngOnInit()中使用。似乎正常的TestBed.createComponent(MyComponent)不会叫ngOnInit()。所以我必须这样做才能获得价值。否则只有一个占位符span

所以,我的最终代码如下所示:

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

    const matSelectValueObject: HTMLElement = fixture.debugElement.query(By.css('.mat-select-value')).nativeElement;
    component.ngOnInit();
    fixture.detectChanges();

    const innerSpan = matSelectValueObject.children[0].children[0]; // for getting the inner span

    expect(innerSpan.innerHTML).toEqual(3); // or '3', I did not test that
});

顺便说一下,我使用的是Angular 7,以防万一。


0
投票

这个在Angular 7中为我工作

const debugElement = fixture.debugElement;
const matSelect = debugElement.query(By.css('.mat-select-trigger')).nativeElement;
matSelect.click();
fixture.detectChanges();
const matOption = debugElement.query(By.css('.mat-option'))[0].nativeElement;
matOption.click();
fixture.detectChanges();
fixture.whenStable().then( () => {
   const inputElement: HTMLElement = debugElement.query(By.css('.ask-input')).nativeElement;
   expect(inputElement.innerHTML.length).toBeGreaterThan(0);
});
© www.soinside.com 2019 - 2024. All rights reserved.