Flutter Golden Testing Skill
This skill outlines the step-by-step process for implementing and updating golden tests for Flutter widgets.
Step 1: Validation & Setup
- Check Dependencies: Ensure
alchemistis present in thedev_dependenciesofpubspec.yaml. If it is missing, install it:flutter pub add --dev alchemist - Directory Structure: Create a
goldens/directory adjacent to your target test file to store the generated.pngreference files.
Step 2: Test Scaffolding
Create the test file named [widget_name]_test.dart (or [widget_name]_golden_test.dart).
- Imports: Import the necessary packages (
package:flutter_test/flutter_test.dartandpackage:alchemist/alchemist.dart). - Setup Fonts/Assets: Call
loadAppFonts()(if applicable) before running the tests to prevent text from rendering as the Ahem font.
Step 3: Implementation
Implement the test using alchemist APIs instead of the standard testWidgets.
- Use
goldenTest: Define your test using thegoldenTestfunction. - Mock Externalities:
- Disable or replace infinite animations (e.g.,
CircularProgressIndicator). - Mock network image requests (e.g., using
mocktail_image_networkornetwork_image_mock).
- Disable or replace infinite animations (e.g.,
- Matrix Testing: Use
GoldenTestGroupandGoldenTestScenarioto lay out all possible widget states (e.g., loading, success, error) and variations (light/dark mode, text scaling) within a single test execution.
Step 4: Generation and Verification
- Generate Goldens: Run the following command to generate or update the reference images:
flutter test --update-goldens - Verify Output: Check that the
.pngfiles were correctly generated in thegoldens/directory. - Gitignore Failures: Ensure
**/failures/is in the project's.gitignoreso test failure artifacts are not accidentally committed.
Step 5: Updating Existing Goldens
If you are modifying an existing widget that already has golden tests, run the update command (flutter test --update-goldens) to regenerate the images. Never modify the .png files manually.