Cypress e2e test with Angular Material mat-select can't set a select value

Discussão em 'Angular' iniciado por user2385520, Janeiro 28, 2025.

  1. user2385520

    user2385520 Guest

    I am trying to set a mat-option value with a Cypress test in Angular 9. I have tried all of the following workarounds below and none of them works. I am using Angular Material and the mat-select component with dynamic ngFor mat-options. The selector works fine but I can't set it or get the click to work correctly on the mat-select.

    Example mat-select I am using

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


    failed attempts to get the click set

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


    or

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


    or

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


    or

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


    or

    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);
    });
    });
    });


    None of these worked and basically threw an error saying mat-option can't be found. Most of the time the mat-select popup did not even appear after the click event. I have also tried adding wait calls to see if it was an async issue but the same thing happened. Any help would be greatly appreciated. I have attached some references below that I have also tried. I am confused why the popup does not appear consistently from mat-select on a click event and if it does it can't find any options.

    REFERENCES:


    Continue reading...

Compartilhe esta Página