使用Angular Material mat-select进行Cypress e2e测试无法设置选择值

问题描述 投票:0回答:1

我正在尝试使用Angular 9中的Cypress测试来设置mat-option值。我已经尝试了以下所有以下变通办法,但都无济于事。我正在将Angular Material和mat-select组件与动态ngFor mat-options一起使用。选择器工作正常,但我无法设置它,也无法单击以使它在垫选择器上正常工作。

我正在使用的示例垫选择

<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>

获取点击次数失败的尝试

cy.get('[data-cy=beginYear-select]').contains(yearValue.toString()).click();

cy.get('mat-select').first().click({ force: true }).get('mat-option').contains(yearValue.toString()).click()

cy.get('mat-select[formcontrolname="beginYear"]').first().click().get('mat-option').contains(yearValue.toString()).click();

cy.get('mat-select[formcontrolname="beginYear"]').then(() => {
      cy.get('mat-option').contains(endYear.toString()).click();
      })

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(() => {
      // After click, mat-select should contain the text of the selected option
      cy.get(`[formcontrolname="${formControlName}"]`).contains(selectOption);
    });
  });
});

这些都不起作用,并且基本上抛出了一个错误,指出找不到mat-option。大多数情况下,单击事件后,垫选择弹出窗口甚至都没有出现。我还尝试添加等待调用以查看是否是异步问题,但发生了相同的事情。任何帮助将不胜感激。我在下面附加了一些我也尝试过的参考文献。我感到困惑,为什么单击事件中的mat-select弹出窗口不能始终显示,如果弹出,则找不到任何选项。

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

javascript angular angular-material2 cypress angular9
1个回答
0
投票

我认为您需要先通过'#'进行mat-select选择,才能通过其ID正确选择它。每个mat-select都像一个输入,因此在大多数情况下,它将类似于“ mat-select-1”,“ mat-select-2” ...等。我先通过单击我的Mat-select而不是从该选择中单击一个选项来使其起作用。

cy.get('#mat-select-1').click()
cy.get('#mat-option-2').click()

尽管我只是没有使它与赛普拉斯的select()一起使用,但这是一种解决方法。

© www.soinside.com 2019 - 2024. All rights reserved.