setUpFakePreferences function

  1. @visibleForTesting
Future<FakeSharedPreferencesStore> setUpFakePreferences(
  1. Map<String, Object> data
)

Resets all shared preference-related singletons and injects the given map of data as the initial stored data within shared preferences.

Returns a FakeSharedPreferencesStore which contains a log of all method calls made to the platform.

Implementation

@visibleForTesting
Future<FakeSharedPreferencesStore> setUpFakePreferences(
  Map<String, Object> data,
) async {
  // Reset the singleton instances for shared preferences and streaming
  // shared preferences.
  SharedPreferences.setMockInitialValues({}); // This also clears singleton
  debugResetStreamingSharedPreferencesInstance();

  // Add the prefix to the key if it doesn't start with one yet.
  final newData = data.map((key, value) {
    var newKey = key;
    if (!key.startsWith(_prefix)) {
      newKey = '$_prefix$key';
    }

    return MapEntry<String, Object>(newKey, value);
  });

  // Create and set a new fake shared preference store to hold shared
  // preferences values.
  final store = FakeSharedPreferencesStore(newData);
  SharedPreferencesStorePlatform.instance = store;

  // Update the variable used by streaming shared preferences for obtaining
  // the shared preference instance. This ensures the latest shared pref
  // object with our new fake store instance is used.
  debugObtainSharedPreferencesInstance = SharedPreferences.getInstance();

  // Obtain the shared preferences to ensure a singleton exists
  await SharedPreferences.getInstance();

  // Clear any logs that occured while obtaining the shared pref singleton
  store.log.clear();

  return store;
}