sodcalculator

10 Tech How-To

Testing Ionic Apps with Cypress: A How-To

Guide 10-48307 · Updated · Step by step

This guide walks you through setting up and running end-to-end tests for Ionic mobile apps using Cypress. You’ll learn how to configure Cypress to work with the Ionic framework, write tests that interact with your UI, and handle common pitfalls like async rendering and device-specific behavior. By the end, you’ll have a repeatable test setup that runs in a browser, giving you fast feedback on your app’s core flows.

What You’ll Need

  • An existing Ionic app (Angular, React, or Vue) with the Ionic CLI installed.
  • Node.js (v18 or later) and npm installed.
  • Basic familiarity with Cypress and JavaScript/TypeScript.
  • Your app should be able to run locally in a browser (e.g., ionic serve).

Step-by-Step

  1. Install Cypress
    In your Ionic project root, run: npm install --save-dev cypress. This adds Cypress as a dev dependency.
  2. Add Cypress scripts
    In package.json, add scripts: "cypress:open": "cypress open" and "cypress:run": "cypress run". This lets you launch the Cypress test runner easily.
  3. Configure Cypress
    Run npx cypress open once to generate the cypress.config.ts file and the cypress/ folder. In the config file, set baseUrl to your local dev server URL (e.g., http://localhost:8100 for Ionic). Also set viewportWidth and viewportHeight to simulate a mobile device, like 390×844.
  4. Start your Ionic app
    Run ionic serve in a separate terminal. Make sure it’s accessible at the baseUrl you configured.
  5. Write your first test
    In cypress/e2e/, create a file like home.cy.ts. Start with a simple test that visits the app and checks for a known element. For example:
    describe('Home Page', () => {
      it('displays the app title', () => {
        cy.visit('/');
        cy.contains('My Ionic App').should('be.visible');
      });
    });
  6. Use Ionic-specific selectors
    Ionic components render custom elements like ion-button, ion-input, and ion-item. Use Cypress’s cy.get('ion-button') or better, add data-cy attributes to your elements for stable selectors. For example: <ion-button data-cy="submit-btn">Submit</ion-button> then cy.get('[data-cy=submit-btn]').
  7. Interact with inputs
    For Ionic inputs, use cy.get('ion-input').type('text') but note that Ionic wraps the native input inside a shadow DOM. Use cy.get('ion-input').find('input').type('text') to target the actual input element. Alternatively, use cy.get('ion-input').shadow().find('input') if needed.
  8. Test navigation and routing
    Ionic uses its own router. To navigate, use cy.visit('/page2') or click a button that triggers navigation. For example: cy.get('[data-cy=nav-btn]').click(); cy.url().should('include', '/page2');
  9. Handle async rendering
    Ionic components often animate in. Use Cypress’s built-in retry-ability: cy.get('[data-cy=element]').should('be.visible') will retry until the element appears. Avoid fixed waits like cy.wait(1000); instead rely on assertions.
  10. Mock network requests
    Use cy.intercept() to mock API calls. For example: cy.intercept('GET', '/api/data', { fixture: 'data.json' }). This makes tests deterministic and fast.
  11. Run the tests
    In the Cypress test runner, click on your test file to run it. For headless runs, use npm run cypress:run.

Common Mistakes

  • Not using baseUrl: Forgetting to set baseUrl leads to full URLs in cy.visit() and can break relative paths.
  • Targeting shadow DOM elements incorrectly: Ionic uses shadow DOM, so standard selectors may not find inner elements. Use .shadow() or find the native element inside.
  • Relying on hard-coded waits: Fixed waits make tests flaky. Use Cypress’s retry-ability and assertions instead.
  • Testing on desktop viewport only: If you don’t set a mobile viewport, you might miss responsive layout issues.
  • Ignoring Ionic’s animations: Some elements are hidden during animations. Wait for them to become visible with assertions.

Tips

  • Use data-cy attributes: They are stable and independent of CSS classes or text changes.
  • Test with real device dimensions: Set viewport to match a common phone (e.g., 390×844) to catch layout issues.
  • Group tests by feature: Keep your test files organized by page or feature to make debugging easier.
  • Use fixtures for test data: Store mock responses in cypress/fixtures/ to keep tests clean.
  • Run Cypress in CI: Add a CI job that runs npm run cypress:run after building your app.

Troubleshooting

Cypress can’t find your app at baseUrl: Make sure ionic serve is running and the port matches. If you’re using a different port, update baseUrl accordingly.

Selectors fail on Ionic components: Try using cy.get('ion-input').find('input') or cy.get('ion-button').shadow(). If still failing, inspect the element in the Cypress test runner to see the actual DOM structure.

Tests pass locally but fail in CI: Check that your CI environment can access the app (e.g., start the server in a background process). Also ensure the viewport is set correctly.

Animations cause flaky tests: Disable animations in your app for tests by adding a global CSS override or using cy.clock() to control timers.

Cypress doesn’t support certain Web APIs: Some Ionic plugins rely on native APIs. Mock them with cy.stub() or cy.intercept().

Frequently Asked Questions

Can I test Ionic apps on a real device with Cypress?

Cypress runs in a browser, so it can’t test native device features. Use it for web-based UI testing; for native functionality, use Appium or Detox.

Do I need to use TypeScript with Cypress?

No, you can write tests in JavaScript. TypeScript is optional but recommended for better IDE support.

How do I test Ionic’s camera or geolocation?

These are native plugins and won’t work in a browser. Stub them with cy.stub() or mock the plugin module.

Can I test Capacitor-specific features?

Capacitor plugins are not available in the browser. You can mock them using cy.stub() or use a mock library.

Is Cypress free for commercial use?

Yes, Cypress is open-source and free to use, including for commercial projects.

How do I run Cypress tests in a CI pipeline?

Use the cypress run command in your CI script. Start your app server first, then run the tests.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →