Search code examples
firebasefluttergoogle-cloud-firestorefirebase-cliflutter-test

Setting Firestore Emulator with Flutter test hangs


I'm trying to write Unit Tests using Firestore Emulator.

I've started the emulator with the following command :

firebase emulators:start --only firestore

The test is as follow :

  testWidgets('should retrieve correct item', (tester) async {
    await Firestore.instance.settings(
      host: "127.0.0.1:8080",
      sslEnabled: false,
      persistenceEnabled: false,
    );

    var ref = await Firestore.instance
      .collection('books')
      .add({ 'title': 'title'});

    // Fetch item by id
    var resp = await Firestore.instance
      .collection('books')
      .document(ref.documentID)
      .get();

    expect(resp, isNotNull);

  });

The problem is that the code hangs on the .settings() method and never proceed to the next steps.

Fun fact is when I stop the emulator, the tests acts the same and hangs on the .add() method, making me wonder if the way I'm doing it is the right way.


Solution

  • You should take a look at Dependency Injection, that's not the right way to test stuff. Probably the test hangs as it can't communicate with Firebase at that address.

    Every time you have a piece of code that's hard to test, either because it's slow or needs network access (APIs, Databases etc.) you should mock it.

    I recommend you take a look at the Mockito and provider packages.

    Use Provider to inject dependencies (Firebase.instance on this case) into your actual code and when testing you can inject a mock of Firebase that actually does nothing instead using Mockito and still validate all calls to Firebase were correct.