Home > Enterprise >  How to click a calendar element using cypress?
How to click a calendar element using cypress?

Time:07-07

I'm writing an e2e test that is attempting to click a calendar element on the page. Cypress is actually clicking a number once I open the calendar, but it won't click the Done button afterwards.

Here's the inspected element: Inspect

Here's the date picker: Date Picker

Here is the code:

      <div style="text-align: center;">
        <ion-datetime presentation="date" *ngIf="showPicker" display-format="MM/DD/YYYY" min="1900-01-01"
          placeholder="*Enter your date of birth" formControlName="dateOfBirth" (ionChange)="dateChanged($event)"
          showDefaultButtons="true" (ionCancel)="showPicker = false;">
        </ion-datetime>
      </div>

I've tried using the default ID on the confirm button shown in the screenshot.

This didn't work: cy.get('ion-datetime').find('#confirm-button').click(); nor cy.get('#confirm-button').click();

Any help would be greatly appreciated.

CodePudding user response:

You have some elements with shadow DOM on that page, to avoid problems with that try adding the setting includeShadowDom: true to the test.

With that in place, both your commands work

it('tests the calendar', {includeShadowDom: true}, () => {

  cy.get('ion-datetime').find('#confirm-button').click();   // passes
    
  cy.get('#confirm-button').click();                        // passes
})

It can also be set globally in cypress.config.js

import { defineConfig } from "cypress";

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
    
  },
  includeShadowDom: true
});

CodePudding user response:

The Done button comes with an id in the DOM. It's best to use that identifier for your test since id should never change during a release. Using your second example (which targets the id), you'll want to correct the syntax.

It should be

cy.get('[id="confirm-button"]').click();

If that still does not work, try to include the tag type:

cy.get('ion-button[id="confirm-button"]').click();

CodePudding user response:

If you have other elements which require traversing Shadow DOM then it's a good practice to write includeShadowDom: true in your cypress config file.

Then You can directly use the command:

cy.get('#confirm-button').click()
  • Related