How to set custom timeouts for a test with async future in Dart?
#Dart #testingdart #flutter #unit_test
Table of contents
No headings in the article.
Let's say you have a future async task that makes an external call and should ideally finish in under 2 seconds and you want to write a test for the same.
class MockClass {
Future<void> initialize() async {
await Future.delayed(const Duration(seconds: 1));
_isInitialized = true;
}
}
Here's how you can do it
MockClass object = MockClass();
test('should be able to initialize in under 2 seconds', () async {
await object.initialize(); // This is the function that should
expect(object.isInitialized, true);
},
timeout: const Timeout(
Duration(seconds: 2),
));
});
The output: ✓ Mock Authentication should be able to initialize in under 2 seconds
Note the Timeout class where you can set the duration.