fluttergoogle-cloud-firestorefirebase-tools

Firebase.initializeApp() works in main() but fails in setUpAll() with PlatformException(channel-error) during unit testing with Firebase Emulator


I am trying to run unit tests for my Flutter project that uses Firebase Firestore, and I want to test it with the Firebase Emulator. I am able to initialize Firebase and connect to the Firestore Emulator successfully when running the app normally in the main() function, but I get an error when trying to initialize Firebase within the setUpAll() function in my test suite.

This code works as expected when running the app normally:

void main() async {
 WidgetsFlutterBinding.ensureInitialized();
 await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
 runApp(const MyApp());
}

When I try to initialize Firebase within setUpAll() in my test file, I get the following error:

PlatformException(channel-error, Unable to establish connection on channel., null, null) package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart 210:7 FirebaseCoreHostApi.initializeCore

Here is my test file:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:task_manager/data/model/user_model.dart';
import 'package:task_manager/data/repository/user_repository/firebase_user_repository.dart';
import 'package:task_manager/firebase_options.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  late FirebaseFirestore firestore;
  late FirebaseUserRepository userRepository;

  setUpAll(() async {
    await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
    FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8080);
  });

  setUp(() async {
    userRepository = FirebaseUserRepository(userCollectionRef: FirebaseFirestore.instance.collection('users'));

    await FirebaseFirestore.instance.terminate();
    await FirebaseFirestore.instance.clearPersistence();
  });

  group('test addUser', () {
    test('Should add a user and retrieve it from Firestore', () async {
      final user = UserModel(id: '1', name: 'bob', email: 'bob@gmail.com');
      final userMap = user.toMap();
      await userRepository.addUser(user.id, userMap);
    });
  });
}


Solution

  • I managed to find the solution. There are 2 things that need to be done:

    1. Start the android/ios emulator.

    2. Move the testing file into /integration_test folder.

    After that you will be able to interact with the Firebase emulator.