Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make selection using cypress in Angular if you're using material forms

I have a form that looks something like this:

<form class="col s12" materialize [formGroup]="newUserForm">
...
    <div class="row">
    <div class="input-field col m4 s12">
        <select formControlName="genderBound" materialize="material_select" id="gender" name="test">
            <option value="" disabled selected name="chooseGender">Choose gender</option>
            <option *ngFor="let gender of genders">{{gender}}</option>
        </select>
        <label for="gender">Gender</label>
    </div>
...

When I try to use cypress to select the dropdown menu, it tells me that it's not visible. When I follow the explanatory URL that cypress provides, it suggest that I use {force: true} inside my click. This allowed my test to pass, but never actually seemed to select the items.

I also followed the solutions provided here, and implemented a jQuery click on the actual option (Note that my select and option tags are not md-select and md-option tags)

sample.spec.js in my cypress directory:

...
it('signs up a new user', () =>{
    cy.get('button[id=new-account-button]').click();
    cy.get('input[id=affiliation]').type(affiliation);
    cy.get('input[id=password]').type(pass);
    cy.get('input[id=userName]').type(name);
    cy.get('input[id=email]').type(email);

    //Now the options
    cy.get('[name="chooseGender"]').click({force: true});
    cy.get('option').contains("Female").then(option =>{
      cy.wrap(option).contains("Female");
      option[0].click();
    });
...

I suppose there's two things I don't quite understand:

  1. Why wasn't an option actually selected?
  2. Why did the test pass despite this?

I provide a repo with my exact issue below:

git clone https://github.com/Atticus29/dataJitsu.git
cd dataJitsu
git checkout cypress-SO

Make an api-keys.ts file in /src/app and populate it with the text to follow

npm install
ng serve

(In a separate terminal tab)

npm run e2e

api-keys.ts:

export var masterFirebaseConfig = {
    apiKey: "AIzaSyCaYbzcG2lcWg9InMZdb10pL_3d1LBqE1A",
    authDomain: "dataJitsu.firebaseapp.com",
    databaseURL: "https://datajitsu.firebaseio.com",
    storageBucket: "",
    messagingSenderId: "495992924984"
  };

export var masterStripeConfig = {
  publicApiTestKey: "pk_test_NKyjLSwnMosdX0mIgQaRRHbS",
  secretApiTestKey: "sk_test_6YWZDNhzfMq3UWZwdvcaOwSa",
  publicApiKey: "",
  secretApiKey: ""
};
like image 412
Atticus29 Avatar asked Aug 06 '18 01:08

Atticus29


2 Answers

For mat-select in Angular 7+ you have to use promises to wait for the options in the modal cdk-overlay to become available.

Here is a helper function for reuse:

function selectMaterialDropDown(formControlName, selectOption) {
  cy.get(`[formcontrolname="${formControlName}"]`).click().then(() => {
    cy.get(`.cdk-overlay-container .mat-select-panel .mat-option-text`).should('contain', selectOption);
    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);
    });
  });
}

Call function:

selectMaterialDropDown('myMatSelectControlName', 'OptionTextToSelect');

like image 91
Enrico Saunders Avatar answered Nov 04 '22 06:11

Enrico Saunders


I found the following test to work with your repository (Latest commit 353633c),

describe('Test Gender Select', () => {

  before(function () {
    cy.visit('http://localhost:4200/')
  })

  it('signs up a new user', () => {
    cy.get('button').contains('Create New Account').click();

    cy.get('#gender').select('Female', {
      force: true
    });
    cy.get('#gender').contains('Female')
  });
});

You can see from the Cypress test runner that it has indeed selected the Female option, so I believe it covers the aim of your original test.

If I try to use click() like so

cy.get('#gender').click({
  force: true
});

cypress gives the message

CypressError: cy.click() cannot be called on a element. Use cy.select() command instead to change the value.

So, following this instruction and using

cy.get('#gender').select('Female');

gives the following error message about visibility, which seems to be standard for a select using material design (both angular-material and materialize).

CypressError: Timed out retrying: cy.select() failed because this element is not visible ... Fix this problem, or use {force: true} to disable error checking.

so using { force: true } option on cy.select() fixes this problem.

I understand the visibility issue occurs because material design covers the parent with the options list, and Cypress uses criteria for visibility based on the parent (see this question), although now the force option works (with Cypress v3.0.3).

like image 5
Richard Matsen Avatar answered Nov 04 '22 07:11

Richard Matsen