capacitor-testing
Complete testing guide for Capacitor apps covering unit tests, integration tests, E2E tests, and native testing. Includes Jest, Vitest, Playwright, Appium, and native testing frameworks. Use this skill when users need to test their mobile apps.
What this skill does
# Testing Capacitor Applications
Comprehensive testing strategies for Capacitor mobile apps.
## When to Use This Skill
- User wants to add tests
- User asks about testing strategies
- User needs E2E testing
- User wants to mock native plugins
- User needs CI testing setup
## Testing Pyramid
```
/\
/ \ E2E Tests (Few)
/----\ - Real devices
/ \ - Full user flows
/--------\ Integration Tests (Some)
/ \ - Component interactions
/------------\ - API integration
/ \ Unit Tests (Many)
/----------------\ - Pure functions
- Business logic
```
## Unit Testing
### Setup with Vitest
```bash
npm install -D vitest @vitest/coverage-v8
```
```typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
},
setupFiles: ['./src/test/setup.ts'],
},
});
```
### Mock Capacitor Plugins
```typescript
// src/test/setup.ts
import { vi } from 'vitest';
// Mock @capacitor/core
vi.mock('@capacitor/core', () => ({
Capacitor: {
isNativePlatform: vi.fn(() => true),
getPlatform: vi.fn(() => 'ios'),
isPluginAvailable: vi.fn(() => true),
},
registerPlugin: vi.fn(),
}));
// Mock @capacitor/preferences
vi.mock('@capacitor/preferences', () => ({
Preferences: {
get: vi.fn(),
set: vi.fn(),
remove: vi.fn(),
clear: vi.fn(),
},
}));
// Mock @capgo/capacitor-native-biometric
vi.mock('@capgo/capacitor-native-biometric', () => ({
NativeBiometric: {
isAvailable: vi.fn().mockResolvedValue({
isAvailable: true,
biometryType: 'touchId',
}),
verifyIdentity: vi.fn().mockResolvedValue({}),
setCredentials: vi.fn().mockResolvedValue({}),
getCredentials: vi.fn().mockResolvedValue({
username: '[email protected]',
password: 'token',
}),
},
}));
```
### Unit Test Examples
```typescript
// src/services/auth.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AuthService } from './auth';
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
describe('AuthService', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('biometricLogin', () => {
it('should authenticate with biometrics', async () => {
const authService = new AuthService();
const result = await authService.biometricLogin();
expect(NativeBiometric.verifyIdentity).toHaveBeenCalledWith({
reason: 'Authenticate to login',
title: 'Biometric Login',
});
expect(result).toBe(true);
});
it('should return false when biometrics unavailable', async () => {
vi.mocked(NativeBiometric.isAvailable).mockResolvedValueOnce({
isAvailable: false,
biometryType: 'none',
});
const authService = new AuthService();
const result = await authService.biometricLogin();
expect(result).toBe(false);
});
it('should handle user cancellation', async () => {
vi.mocked(NativeBiometric.verifyIdentity).mockRejectedValueOnce(
new Error('User cancelled')
);
const authService = new AuthService();
const result = await authService.biometricLogin();
expect(result).toBe(false);
});
});
});
```
### Testing Utilities
```typescript
// src/test/utils.ts
import { Capacitor } from '@capacitor/core';
import { vi } from 'vitest';
export function mockPlatform(platform: 'ios' | 'android' | 'web') {
vi.mocked(Capacitor.getPlatform).mockReturnValue(platform);
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(platform !== 'web');
}
export function mockPluginAvailable(available: boolean) {
vi.mocked(Capacitor.isPluginAvailable).mockReturnValue(available);
}
// Usage in tests
describe('Platform-specific behavior', () => {
it('should use iOS-specific code on iOS', () => {
mockPlatform('ios');
// Test iOS behavior
});
it('should use Android-specific code on Android', () => {
mockPlatform('android');
// Test Android behavior
});
});
```
## Component Testing
### React Testing Library
```bash
npm install -D @testing-library/react @testing-library/user-event
```
```typescript
// src/components/LoginButton.test.tsx
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoginButton } from './LoginButton';
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
describe('LoginButton', () => {
it('should show biometric option when available', async () => {
render(<LoginButton />);
await waitFor(() => {
expect(screen.getByText('Login with Face ID')).toBeInTheDocument();
});
});
it('should call biometric auth on click', async () => {
const user = userEvent.setup();
render(<LoginButton />);
const button = await screen.findByRole('button', { name: /face id/i });
await user.click(button);
expect(NativeBiometric.verifyIdentity).toHaveBeenCalled();
});
});
```
### Vue Test Utils
```bash
npm install -D @vue/test-utils
```
```typescript
// src/components/LoginButton.spec.ts
import { mount, flushPromises } from '@vue/test-utils';
import LoginButton from './LoginButton.vue';
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
describe('LoginButton', () => {
it('should render biometric button', async () => {
const wrapper = mount(LoginButton);
await flushPromises();
expect(wrapper.text()).toContain('Login with Biometrics');
});
it('should trigger authentication on click', async () => {
const wrapper = mount(LoginButton);
await flushPromises();
await wrapper.find('button').trigger('click');
expect(NativeBiometric.verifyIdentity).toHaveBeenCalled();
});
});
```
## E2E Testing
### Playwright for Web
```bash
npm install -D @playwright/test
npx playwright install
```
```typescript
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
use: {
baseURL: 'http://localhost:5173',
trace: 'on-first-retry',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'Mobile Safari',
use: { ...devices['iPhone 14'] },
},
{
name: 'Mobile Chrome',
use: { ...devices['Pixel 7'] },
},
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:5173',
reuseExistingServer: !process.env.CI,
},
});
```
```typescript
// e2e/login.spec.ts
import { test, expect } from '@playwright/test';
test.describe('Login Flow', () => {
test('should login with email and password', async ({ page }) => {
await page.goto('/login');
await page.fill('[data-testid="email"]', '[email protected]');
await page.fill('[data-testid="password"]', 'password123');
await page.click('[data-testid="login-button"]');
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('h1')).toContainText('Welcome');
});
test('should show error for invalid credentials', async ({ page }) => {
await page.goto('/login');
await page.fill('[data-testid="email"]', '[email protected]');
await page.fill('[data-testid="password"]', 'wrong');
await page.click('[data-testid="login-button"]');
await expect(page.locator('[data-testid="error"]')).toBeVisible();
});
});
```
### Appium for Native
```bash
npm install -D webdriverio @wdio/appium-service @wdio/mocha-framework
```
```typescript
// wdio.conf.ts
export const config: WebdriverIO.Config = {
runner: 'local',
specs: ['./e2e/native/**/*.spec.ts'],
capabilities: [
{
platformName: 'iOS',
'appium:deviceName': 'iPhone 15',
'appium:platformVersion': '17.0',
'appium:app': './ios/ApRelated in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.