You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 9中Cypress测试无法设置mat-select选项值求助

Angular 9 + Cypress:mat-select动态选项测试失败求助

我在Angular 9项目里用Cypress写e2e测试,碰到个头疼的问题——给Angular Material的mat-select组件选值怎么都不行。这个组件是用*ngFor动态生成mat-option的,我能正常定位到select选择器,但就是没法触发点击或者设置选中值。

我用到的mat-select示例代码

<div fxLayout="row" fxLayoutAlign="space-between">
  <mat-form-field>
    <mat-label>Begin Year</mat-label>
    <mat-select formControlName="beginYear" data-cy="beginYear-select">
      <mat-option *ngFor="let year of beginYearOptions" [value]="year">
        {{ year }}
      </mat-option>
    </mat-select>
  </mat-form-field>
</div>

已经试过但全都无效的方法:

  • 方法1:直接通过data-cy定位后找文本点击
    cy.get('[data-cy=beginYear-select]').contains(yearValue.toString()).click();
    
  • 方法2:强制点击第一个mat-select后找选项
    cy.get('mat-select').first().click({ force: true }).get('mat-option').contains(yearValue.toString()).click()
    
  • 方法3:通过formControlName定位后点击选项
    cy.get('mat-select[formcontrolname="beginYear"]').first().click().get('mat-option').contains(yearValue.toString()).click();
    
  • 方法4:在then回调里找选项
    cy.get('mat-select[formcontrolname="beginYear"]').then(() => { cy.get('mat-option').contains(endYear.toString()).click(); })
    
  • 方法5:自定义Cypress命令selectMaterialDropDown
    Cypress.Commands.add('selectMaterialDropDown', (formControlName, selectOption) => {
      cy.get(`[formcontrolname="${formControlName}"]`).click().then(() => {
        cy.get(`.cdk-overlay-container .mat-select-panel .mat-option-text`).should('contain', selectOption);
        console.log('PASSED!!!')
        cy.get(`.cdk-overlay-container .mat-select-panel .mat-option-text:contains("${selectOption}")`).first().click().then(() => {
          cy.get(`[formcontrolname="${formControlName}"]`).contains(selectOption);
        });
      });
    });
    

这些方法要么报错找不到mat-option,多数时候连点击mat-select后的弹窗都不出现。我试过加wait解决异步问题,但结果还是一样。现在我特别困惑:为什么mat-select的弹窗没法稳定触发?就算触发了,为什么找不到对应的选项?有没有人能帮我看看问题出在哪?

我参考过的资料:

  • Make selection using cypress in Angular if you're using material forms
  • select dropdownlist item using cypress
  • How to select an option with Angular Material 2 and Protractor?
  • Cypress: Test if element does not exist

内容的提问来源于stack exchange,提问作者user2385520

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:58:02