Testing
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
An Ionic app is mostly an Angular web app, so most of it can be tested with ordinary web tools in a browser or in
Node, quickly and without a device. Only the thin layer that talks to real hardware needs a simulator or a phone.
A good strategy pushes as much verification as possible down to the cheap layers and keeps a small number of slow,
real-device checks on top. This page applies that idea to Trailhead (com.example.trailhead) on
Ionic Framework 9.0.10, Capacitor 8.6.0, Angular 22.2.5 and Playwright 1.65.0.
For Angular’s own testing guide see Angular testing; for the browser-automation background see end-to-end testing. The section home is Hybrid Apps.
The Test Pyramid
| Layer | Runs on | Covers |
|---|---|---|
Unit and component |
Node or a headless browser |
Services, pure logic, components with their templates, Ionic standalone components |
Browser E2E |
Chromium, Firefox, WebKit |
Full flows against the web build with the network stubbed |
Native E2E |
Emulator, simulator, device |
Permissions, camera, deep links, install and upgrade behaviour |
Manual |
Real devices |
Gestures, performance, hardware quirks |
Unit and Component Tests with the Angular CLI
The Angular CLI runs tests with:
npx ng test
The test runner behind that command depends on the Angular version and on how the project was generated. Recent
Angular releases favour Vitest, while older projects use Jasmine with Karma. Both are
configured in angular.json and use the same describe, it and expect style, so the examples below apply to
either; check your project’s test target to see which one you have, and consult the Angular testing guide for
runner-specific flags.
A Service Test
Services that use HttpClient are tested with the testing providers, which intercept requests without a network:
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TrailsApi } from './trails-api';
describe('TrailsApi', () => {
let api: TrailsApi;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
api = TestBed.inject(TrailsApi);
http = TestBed.inject(HttpTestingController);
});
it('loads the trail list', () => {
let result: unknown;
api.list().subscribe((trails) => (result = trails));
const req = http.expectOne('/trails');
expect(req.request.method).toBe('GET');
req.flush([{ id: '1', name: 'Ridge Loop', lengthKm: 6.5, difficulty: 'easy' }]);
expect(result).toEqual([{ id: '1', name: 'Ridge Loop', lengthKm: 6.5, difficulty: 'easy' }]);
http.verify();
});
});
Standalone Ionic Components
Ionic 9 components are used as standalone imports from @ionic/angular/standalone. In a test, import the
component under test; its own imports array pulls in the Ionic pieces it needs.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { provideRouter } from '@angular/router';
import { TrailListPage } from './trail-list.page';
import { TrailService } from './trail.service';
describe('TrailListPage', () => {
let fixture: ComponentFixture<TrailListPage>;
beforeEach(async () => {
const serviceDouble = {
filtered: signal([{ id: '1', name: 'Ridge Loop', lengthKm: 6.5, difficulty: 'easy' }]),
query: signal(''),
load: async () => {},
};
await TestBed.configureTestingModule({
imports: [TrailListPage],
providers: [provideRouter([]), { provide: TrailService, useValue: serviceDouble }],
}).compileComponents();
fixture = TestBed.createComponent(TrailListPage);
fixture.detectChanges();
});
it('renders one item per visible trail', () => {
const items = fixture.nativeElement.querySelectorAll('ion-item');
expect(items.length).toBe(1);
expect(fixture.nativeElement.textContent).toContain('Ridge Loop');
});
});
Ionic-specific considerations:
-
Ionic components are web components. In a unit test environment they are registered but animations, gestures and overlays (
ion-modal,ion-alert) behave differently or lazily; assert on the data and the rendered text, and cover overlay behaviour in browser E2E tests. -
Call
provideIonicAngular()in the test providers if a component usesModalController,ToastControlleror other Ionic services. -
Prefer testing logic in services and stores, and keep page components thin so there is little to test through the DOM.
-
Provide a router double (
provideRouter([])or a spy) for pages that navigate.
Mocking Capacitor Plugins
Capacitor plugins call native code. In a browser or Node test most either return web fallbacks or throw "not implemented". Do not fight that at every call site. Instead wrap each plugin in a small injectable service and substitute a test double for the wrapper. Production code depends only on the wrapper:
// src/app/device/camera.service.ts
import { Injectable } from '@angular/core';
import { Camera, CameraResultType } from '@capacitor/camera';
@Injectable({ providedIn: 'root' })
export class CameraService {
async takePhoto(): Promise<string | undefined> {
const photo = await Camera.getPhoto({ resultType: CameraResultType.Uri, quality: 80 });
return photo.webPath;
}
}
// in a test
class FakeCameraService {
async takePhoto(): Promise<string | undefined> {
return 'blob:fake-photo';
}
}
TestBed.configureTestingModule({
providers: [{ provide: CameraService, useClass: FakeCameraService }],
});
The same approach works for GeolocationService, ConnectivityService and TrailsCache. Tests then cover your
logic (what happens when the photo is cancelled, when the position is denied) without touching Capacitor at all.
Keep a few integration checks on the real wrapper in native E2E tests.
End-to-End Tests in a Browser with Playwright
Playwright 1.65.0 drives Chromium, Firefox and WebKit against ng serve or the production build served locally.
Stub the API so tests are deterministic, and treat the app as a normal website.
// e2e/trails.spec.ts
import { test, expect } from '@playwright/test';
test('search filters the trail list', async ({ page }) => {
await page.route('**/v1/trails', (route) =>
route.fulfill({
json: [
{ id: '1', name: 'Ridge Loop', lengthKm: 6.5, difficulty: 'easy' },
{ id: '2', name: 'Summit Trail', lengthKm: 12, difficulty: 'hard' },
],
}),
);
await page.goto('/');
await expect(page.getByText('Ridge Loop')).toBeVisible();
await page.getByPlaceholder('Search trails').fill('summit');
await expect(page.getByText('Ridge Loop')).toBeHidden();
await expect(page.getByText('Summit Trail')).toBeVisible();
});
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: 'e2e',
use: { baseURL: 'http://localhost:4200' },
webServer: { command: 'npm run start', url: 'http://localhost:4200', reuseExistingServer: true },
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'mobile-webkit', use: { ...devices['iPhone 14'] } },
],
});
Emulating a phone viewport and WebKit catches layout and Ionic-component issues early. Playwright does not run the
native shell, so camera and GPS flows go through the same wrapper doubles or through
context.grantPermissions() and context.setGeolocation() in the browser. The Playwright guides on this site start
at End-to-End Testing.
Native End-to-End Tests
To exercise the real app on an emulator, simulator or device, use a mobile automation tool:
| Tool | Notes |
|---|---|
Appium with WebdriverIO |
Standards-based WebDriver for native apps; drive the native shell and switch into the WebView context to use CSS selectors; flexible but needs more setup |
Maestro |
Declarative YAML flows run against an installed app; fast to write and read, good for smoke tests |
# .maestro/log-hike.yaml
appId: com.example.trailhead
---
- launchApp
- tapOn: "Ridge Loop"
- tapOn: "Log a hike"
- inputText: "Great views"
- tapOn: "Save"
- assertVisible: "Hike saved"
Keep native suites small: install, sign-in, one happy path per permission-gated feature, and a deep link. They are slower and flakier than browser tests, so cover logic elsewhere.
Debugging on a Device
-
Android: enable USB debugging, run the app, then open
chrome://inspectin desktop Chrome and choose the WebView under your device. The full Chrome DevTools open against the running app. -
iOS: enable Web Inspector in the device’s Safari advanced settings, enable the Develop menu in desktop Safari, then pick the device and the app’s WebView from the Develop menu.
-
Use Xcode and Android Studio logs for native errors, which never appear in the web console.
-
Debug builds only: iOS WebViews are inspectable for development builds, and Android WebView debugging follows the app’s debuggable flag, so release builds are not inspectable by default.
More device tooling is in Hybrid Apps: IDEs & Tools.
Coverage
Coverage is a signal, not a goal. With the CLI test runner, coverage is enabled with the runner’s coverage option;
the exact flag depends on the runner, so check the output of npx ng test --help for your version. Aim for high
coverage of stores, services and mapping code, and do not chase numbers on template glue. Publish the report in CI
and fail the build only on a meaningful threshold agreed by the team.
In Continuous Integration
Run unit and Playwright tests on every pull request, and the native suites on a schedule or before a release, as described in Building and Releasing. Related reading: Data, Storage and Networking, Ionic Cheat Sheet and, for comparison, React Native.