— Dart, Flutter, Firebase, Unit Tests — 1 min read
Recently I was upgrading some dependencies in a Flutter project that I hadn't touched for a while and my unit tests broke.
The culprit ended up being some changes that had been made to the firebase_analytics package. It's also my fault too because there were some logEvent
calls being used inside code that I was testing in my unit tests. This is the error I was getting that caused the tests to fail:
1[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
I talked about this issue in a previous post earlier this year, and in that case I ended up adding some mocks for FirebaseAnalytics
using mockito.
This time I didn't really feel like going to that amount of effort so I opted for a quick fix. I know that the former is a better option but I thought I'd write about this method too because it could come in handy in other situations.
It turns out that you can actually check whether code is being run as a test or not. You do it using Platform
like this:
1import 'dart:io';2
3final isTest = Platform.environment.containsKey('FLUTTER_TEST');
So if the above returns true, it means that a test is being run.
So I ended up just adding the above line to my code as a check, and used an early return if it was a test. I have an extension method specifically for sending events that looks like this:
1logEvent({Map<String, dynamic>? parameters}) {2 _logger.d('Sending analytics event: $this');3 if (parameters != null) {4 FirebaseAnalytics.instance.logEvent(name: this, parameters: parameters);5 } else {6 FirebaseAnalytics.instance.logEvent(name: this);7 }8}
I changed it to this:
1logEvent({Map<String, dynamic>? parameters}) {2 if (Platform.environment.containsKey('FLUTTER_TEST')) return;3 _logger.d('Sending analytics event: $this');4 if (parameters != null) {5 FirebaseAnalytics.instance.logEvent(name: this, parameters: parameters);6 } else {7 FirebaseAnalytics.instance.logEvent(name: this);8 }9}
And my tests ran with no issues again! Like I said this solution isn't the best so if you want to read about using mocks instead feel free to check my other post out.