easy_localization icon indicating copy to clipboard operation
easy_localization copied to clipboard

Widget using Plural unable to be tested

Open lockieRichter opened this issue 1 year ago • 1 comments

I am unable to run widget tests for a widget that uses the plural extension method.

The tests are failing with the following error

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following LateError was thrown building _OpenWorkCount(dirty):
LateInitializationError: Field '_locale@2908425997' has not been initialized.
...
When the exception was thrown, this was the stack:
#0      Localization._locale (package:easy_localization/src/localization.dart)
#1      Localization.plural (package:easy_localization/src/localization.dart:152:36)
#2      plural (package:easy_localization/src/public.dart:114:31)
#3      StringTranslateExtension.plural (package:easy_localization/src/public_ext.dart:104:10)
...

When I change the widget to use just a standard translation with the .tr extension method the tests pass.

Any help on how to set up my tests so that the locale gets initialised would be great.

Right now I am doing the following in my tests.

void main() async {
  testWidgets('Test', (tester) async {
    TestWidgetsFlutterBinding.ensureInitialized();
    SharedPreferences.setMockInitialValues({});
    EasyLocalization.logger.enableBuildModes = [];
    await EasyLocalization.ensureInitialized();
    await tester.pumpWidget(
      EasyLocalization(
        path: 'assets/translations',
        supportedLocales: const [
          Locale('en', 'US'),
        ],
        child: MaterialApp(
          home: WigetUnderTest(),
        ),
      ),
    );
  });
}

lockieRichter avatar Jan 31 '25 02:01 lockieRichter

Am currently working around this by calling the following block in a setUpAll in my widget tests.

import 'package:easy_localization/easy_localization.dart';
import 'package:easy_localization/src/easy_localization_controller.dart';
import 'package:easy_localization/src/localization.dart';
import 'package:flutter/material.dart';

Future<void> initEasyLocalization(Locale locale) async {
  final localizationController = EasyLocalizationController(
    forceLocale: locale,
    fallbackLocale: locale,
    supportedLocales: [locale],
    path: 'assets/translations',
    useOnlyLangCode: false,
    useFallbackTranslations: false,
    onLoadError: (FlutterError e) {},
    saveLocale: true,
    assetLoader: const RootBundleAssetLoader(),
  );
  await localizationController.loadTranslations();
  Localization.load(
    locale,
    translations: localizationController.translations,
  );
}

lockieRichter avatar Mar 05 '25 03:03 lockieRichter