1: mat-select有4个值,1,2,3,4。
下面的代码很适合select。因此,如果它对读者有帮助,我想分享一下。
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);
});
});任何帮助都是非常感谢的。
发布于 2019-04-05 19:13:38
这个在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);
});发布于 2018-12-11 20:53:24
经过一些测试,我找到了一个答案(至少对我的代码是这样的),希望这对你也有帮助:
当我查看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,以防这很重要。
发布于 2020-03-04 22:55:31
页对象的Helper方法,以按文本设置选项:
public setMatSelectValue(element: HTMLElement, value: string): Promise<void> {
// click on <mat-select>
element.click();
this.fixture.detectChanges();
// options will be rendered inside OverlayContainer
const overlay = TestBed.get(OverlayContainer).getContainerElement();
// find an option by text value and click it
const matOption = Array.from(overlay.querySelectorAll<HTMLElement>('.mat-option span.mat-option-text'))
.find(opt => opt.textContent.includes(value));
matOption.click();
this.fixture.detectChanges();
return this.fixture.whenStable();
}https://stackoverflow.com/questions/52505846
复制相似问题