flutter-core:flutter-testing-quality
Comprehensive Flutter testing and quality assurance guidance covering unit testing, widget testing, integration testing, golden tests, debugging techniques, code coverage, test-driven development, mocking strategies, DevTools profiling, and quality metrics. Use when testing Flutter applications, writing unit tests, widget tests, integration tests, debugging issues, improving test coverage, creating golden files, mocking dependencies, profiling performance, or establishing testing strategies.
What this skill does
# Flutter Testing & Quality
A comprehensive guide to testing and quality assurance in Flutter applications. This skill covers the complete testing pyramid from fast unit tests to comprehensive integration tests, along with debugging techniques, profiling strategies, and quality metrics that ensure your Flutter apps are reliable, maintainable, and performant.
## Philosophy: Testing as a First-Class Citizen
Flutter's testing framework is not an afterthought—it's a core part of the development experience. The framework provides excellent testing APIs that make it genuinely pleasant to write tests. Testing in Flutter follows the testing pyramid: many fast unit tests at the base, a moderate number of widget tests in the middle, and fewer but crucial integration tests at the top.
The key insight is that testing isn't just about catching bugs—it's about designing better APIs, improving code architecture, and giving you confidence to refactor and evolve your codebase. Well-tested Flutter apps are easier to maintain, onboard new developers to, and extend with new features.
## Understanding the Testing Pyramid
Flutter supports three types of tests, each serving a distinct purpose in your quality assurance strategy.
### Unit Tests
Unit tests validate individual functions, methods, and classes in isolation. They are the foundation of your testing strategy because they:
- Run extremely fast (thousands can execute in seconds)
- Provide precise failure messages pointing to exact issues
- Enable test-driven development workflows
- Validate business logic independently of Flutter framework
- Require no special Flutter environment
Unit tests should comprise 60-70% of your test suite. They test pure Dart code: data models, utility functions, business logic, validators, parsers, and state management logic.
### Widget Tests
Widget tests (also called component tests) validate that your UI widgets behave correctly. They:
- Test widgets in isolation from the full app
- Verify widget rendering, layout, and user interactions
- Run faster than integration tests but slower than unit tests
- Can pump widgets, trigger interactions, and verify results
- Use Flutter's testing framework to simulate the widget tree
Widget tests should comprise 20-30% of your test suite. They test individual screens, complex widgets, form behavior, animations, and user interactions without requiring a real device.
### Integration Tests
Integration tests validate complete app flows on real devices or simulators. They:
- Test the entire app as users would experience it
- Verify navigation flows, API integration, and persistence
- Run slowest but provide highest confidence
- Catch issues that unit and widget tests miss
- Require actual device/emulator to execute
Integration tests should comprise 5-10% of your test suite. They test critical user journeys, onboarding flows, checkout processes, and cross-cutting concerns.
## Decision Tree: Choosing the Right Test Type
Use this decision tree to select the appropriate testing approach:
### Question 1: Does it involve UI rendering?
**If NO (pure Dart logic):**
→ Use **Unit Tests**
→ Test with `test()` package
→ No Flutter dependencies needed
→ **Reference**: [Unit Testing](references/unit-testing.md)
**If YES (involves widgets):**
→ Continue to Question 2
### Question 2: Does it require navigation or multiple screens?
**If NO (single widget/screen):**
→ Use **Widget Tests**
→ Test with `testWidgets()`
→ Mock external dependencies
→ **References**: [Widget Testing](references/widget-testing.md), [Mocking Strategies](examples/mocking-strategies.md)
**If YES (multiple screens/full flows):**
→ Use **Integration Tests**
→ Test with `integration_test` package
→ Run on real device/emulator
→ **Reference**: [Integration Testing](references/integration-testing.md)
### Question 3: Do you need visual regression testing?
**If validating pixel-perfect UI:**
→ Use **Golden Tests**
→ Generate golden files for comparison
→ Catch unintended visual changes
→ **Reference**: [Golden Tests](references/golden-tests.md)
## Core Testing Principles
Regardless of which test type you choose, follow these principles:
### 1. Arrange-Act-Assert (AAA) Pattern
Structure every test in three clear phases:
```dart
test('counter increments correctly', () {
// Arrange: Set up test conditions
final counter = Counter(initialValue: 0);
// Act: Execute the operation
counter.increment();
// Assert: Verify the result
expect(counter.value, 1);
});
```
This pattern makes tests readable, maintainable, and easy to debug when they fail.
### 2. Test One Thing at a Time
Each test should verify a single behavior or condition. If a test fails, you should immediately know what broke:
```dart
// Good: Tests one specific behavior
test('login validates empty email', () {
final result = validator.validateEmail('');
expect(result, 'Email cannot be empty');
});
// Bad: Tests multiple unrelated things
test('login validation', () {
expect(validator.validateEmail(''), 'Email cannot be empty');
expect(validator.validatePassword(''), 'Password cannot be empty');
expect(validator.validateEmail('invalid'), 'Invalid email format');
});
```
### 3. Make Tests Independent
Tests should not depend on execution order or shared state. Each test should set up its own data and clean up after itself:
```dart
// Use setUp and tearDown for test isolation
group('UserRepository', () {
late UserRepository repository;
late Database mockDatabase;
setUp(() {
mockDatabase = MockDatabase();
repository = UserRepository(mockDatabase);
});
tearDown(() {
mockDatabase.close();
});
test('saves user correctly', () {
// Test implementation
});
});
```
### 4. Use Descriptive Test Names
Test names should describe what is being tested and the expected outcome:
```dart
// Good: Clear and descriptive
test('formatCurrency converts dollars to formatted string with two decimals', () {});
test('submitForm shows error message when email is invalid', () {});
// Bad: Vague and unclear
test('test1', () {});
test('currency works', () {});
```
### 5. Test Edge Cases and Error Conditions
Don't just test the happy path. Test boundary conditions, null values, empty lists, network failures, and error states:
```dart
group('parseUserAge', () {
test('returns age for valid input', () {
expect(parseUserAge('25'), 25);
});
test('returns null for negative numbers', () {
expect(parseUserAge('-5'), null);
});
test('returns null for non-numeric input', () {
expect(parseUserAge('abc'), null);
});
test('returns null for null input', () {
expect(parseUserAge(null), null);
});
});
```
## Testing Strategy for Different App Components
### Testing State Management
State management logic should be thoroughly unit tested independently of widgets:
- **setState**: Test stateful widgets with widget tests
- **ChangeNotifier/ValueNotifier**: Unit test notifier logic, widget test UI integration
- **Provider/Riverpod**: Mock providers in widget tests
- **BLoC**: Unit test blocs/cubits, widget test UI with BlocProvider
→ **Cross-reference**: flutter-state-management skill
### Testing Navigation and Routing
Navigation requires widget or integration tests:
- Widget tests: Mock Navigator and verify navigation calls
- Integration tests: Test complete navigation flows
- Verify route transitions, deep linking, and route guards
→ **Cross-reference**: flutter-navigation-routing skill
### Testing Network Calls
Network integration requires mocking:
- Unit test: Mock HTTP clients and test response handling
- Widget test: Mock repositories providing data
- Integration test: Use real API or mock server
→ **References**: [Unit Testing](references/unit-testing.md), [Mocking Strategies](examples/mocking-strategies.md)
### Testing Persistence
Database and storage operations require isolation:
- Unit test: Mock database interfaces
- Widget test: Provide test dRelated in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.