Created
April 22, 2024 14:47
-
-
Save fredgrott/70fb2c63fca4af0afb53eadd386ff8be to your computer and use it in GitHub Desktop.
testing localizations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2024 Fredrick Allan Hrott. All rights reserved. | |
// Use of this source code is governed by a BSD-style | |
// license that can be found in the LICENSE file. | |
import 'package:flutter/material.dart'; | |
import 'package:flutter_localizations/flutter_localizations.dart'; | |
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; | |
import 'package:flutter_test/flutter_test.dart'; | |
// General idea is the localizations in the model are referred to as | |
// AppLocalizations.of(appRouterContext).localizationKey | |
// so then we set the same scaffoldMessengerKey var | |
// and appRouterContext as in the app via MaterialApp wrapper | |
// pump the MaterialApp wrapper and child Container and | |
// then we can run tests on models that are using localizations. | |
// | |
// Because I use the scaffoldMessengerKey instead, the MaterialApp | |
// wrapper for the tests can be different than the MaterialApp.router | |
// in the app without any headaches. | |
late final scaffoldMessengerKey; // = GlobalKey<ScaffoldMessengerState>(); | |
void main() { | |
group('localizations tests', () { | |
setUpAll(() { | |
// sets up scaffoldMessengerKey for the MaterialApp wrapper we use | |
scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>(); | |
}); | |
testWidgets('so this would be a model test with localizations', (WidgetTester widgetTester) async { | |
await widgetTester.pumpWidget(MaterialApp( | |
scaffoldMessengerKey: scaffoldMessengerKey, | |
localizationsDelegates: const [ | |
AppLocalizations.delegate, | |
GlobalMaterialLocalizations.delegate, | |
GlobalWidgetsLocalizations.delegate, | |
GlobalCupertinoLocalizations.delegate, | |
], | |
supportedLocales: AppLocalizations.supportedLocales, | |
locale: const Locale('en', 'EN'), | |
home: Container(), | |
)); | |
// still need this according to bug issue 22193, large localizations file failure | |
await widgetTester.pump(); | |
// we do not have to search for Container element for context as we can do | |
BuildContext testContext = scaffoldMessengerKey.currentContext; | |
// and we do our expect testing here | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment