Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Testing and Performance

Unit Testing Ionic Components and Services

Unit test Ionic pages, services and Capacitor plugin calls with Jest, Vitest or Jasmine: arrange, act, assert, mock native plugins, fake timers and keep tests fast.

Mobile releases are slow. A bug that reaches the stores may take days to fix, because review and user updates take time. Tests are your safety net. Ionic projects come with a test runner chosen by the framework: Jasmine and Karma or Jest for Angular, Vitest for Vite based React and Vue projects. The syntax differs slightly, but the ideas are the same: set up a situation, act, check the result.

This lesson shows what to test, how to isolate Capacitor plugins that do not exist in a test environment, and how to write fast, reliable tests. It uses a tiny test runner so you can run the examples here.

What to test

The test pyramid still applies:

  • Many unit tests for logic: services, stores, validators, formatters.
  • Some component tests that render a page and check what the user sees.
  • A few end-to-end tests for critical flows (see End-to-End Testing for Ionic).

Do not test the framework or Ionic itself. Test your decisions: "completing a note updates the count", "an offline save adds an outbox entry".

Arrange, act, assert

Real test for the notes store from State Management in Ionic Apps, Jest or Vitest style, read-only:

TypeScript
import { describe, it, expect, beforeEach } from 'vitest';
import { NotesStore } from './notes.store';

describe('NotesStore', () => {
  let store: NotesStore;
  beforeEach(() => { store = new NotesStore(); });      // fresh state for each test

  it('counts open notes', () => {
    store.add('Tent');
    store.add('Stove');
    store.toggle(store.notes()[0].id);
    expect(store.openCount()).toBe(1);
  });
});

Each test creates its own store, so tests never depend on each other or on order.

Mocking Capacitor plugins

Plugins call native code. In a unit test there is no device, so replace them with fakes. With Vitest or Jest you mock the module:

TypeScript
import { vi, it, expect } from 'vitest';

vi.mock('@capacitor/preferences', () => ({
  Preferences: {
    get: vi.fn().mockResolvedValue({ value: '{"theme":"dark"}' }),
    set: vi.fn().mockResolvedValue(undefined),
  },
}));

import { Preferences } from '@capacitor/preferences';
import { loadSettings } from './settings';

it('reads the saved theme', async () => {
  const settings = await loadSettings();
  expect(settings.theme).toBe('dark');
  expect(Preferences.get).toHaveBeenCalledWith({ key: 'settings' });
});

For code you control, a better design is dependency injection: pass the plugin in, and your function needs no module mocking.

TypeScript
export async function takeAndSave(camera: CameraLike, files: FilesLike) { /* ... */ }

In Angular, services are injected through the framework, and tests provide fakes with TestBed.configureTestingModule({ providers: [{ provide: Storage, useValue: fake }] }).

A tiny test kit

Here is a complete mini runner with test, expect and a spy. Reading it explains what Jest and Vitest do for you.

JS A mini test runner with spies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Fake timers and time

Code with setTimeout, debounce or Date.now() is hard to test with real waiting. Test frameworks provide fake timers (vi.useFakeTimers(), jest.useFakeTimers(), Angular's fakeAsync and tick). You can also design time as an input: pass a now function.

JS Testing a debounce without waiting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Component tests

Component tests render a page with Ionic's web components. Two practical notes:

  1. Ionic components are Web Components that initialize asynchronously. In Angular use fixture.whenStable(); in React Testing Library use await screen.findByText(...) instead of getByText.
  2. Query by what the user sees (text, labels, roles), not by CSS classes.
TSX
import { render, screen, fireEvent } from '@testing-library/react';
import { setupIonicReact } from '@ionic/react';
import Notes from './Notes';

setupIonicReact();

it('adds a note', async () => {
  render(<Notes />);
  fireEvent.change(await screen.findByLabelText('Title'), { target: { value: 'Tent' } });
  fireEvent.click(screen.getByText('Add'));
  expect(await screen.findByText('Tent')).toBeTruthy();
});

If a test needs more than about 15 lines of setup, the unit under test probably does too much. Move the logic out of the component into a plain function or service and test that instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why mock Capacitor plugins in unit tests?

    Native calls cannot run in Node or a test browser, so fakes replace them.
  2. 2. What is the benefit of injecting a plugin into a function?

    Injected dependencies are easy to replace and keep tests simple.
  3. 3. How should a component test look up a button?

    User-facing queries survive refactoring of markup and styling.
  4. 4. What is a fake timer used for?

    Fake timers let you move the clock forward without sleeping.

Summary

  • Test your own logic: stores, services, validators and user-visible behavior.
  • Isolate each test, and follow arrange, act, assert.
  • Replace Capacitor plugins with fakes by mocking modules or injecting dependencies.
  • Control time with fake timers or a clock parameter.
  • Keep components thin so logic is easy to test.

Next: End-to-End Testing for Ionic