Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing kIsWeb constant in flutter

in my code i have a lookup method:

lookup.dart

Future<http.Response> httpLookup(String address) {
    return kIsWeb
        ? _httpClient.get(address)
        : _httpClient.get(
            Uri.https(address, ''),
          );
  }

how can i test the kIsWeb constant during unit testing? this is what i have tried so far but the coverage is not going though.

lookup_test.dart

@TestOn('browser')
void main (){
test('shoud test lookup', () {
    InternetLookup lookup = InternetLookup();
    when(mockInternetLookup.httpLookup(any))
        .thenAnswer((realInvocation) async => http.Response('success', 200));
    lookup.httpLookup('www.google.com');
  });
}
like image 362
Abiud Orina Avatar asked Aug 03 '26 15:08

Abiud Orina


2 Answers

You can to use an Interface and to mock it.

abstract class IAppService {
  bool getkIsWeb();
}

class AppService implements IAppService {
  bool getkIsWeb() {
    return kIsWeb;
  }
}

In the tests, you must to use like as

class MockAppService extends Mock implements IAppService {}

...

when(appService.getkIsWeb())
        .thenAnswer((realInvocation) => true);
like image 63
Filipe Piletti Plucenio Avatar answered Aug 05 '26 08:08

Filipe Piletti Plucenio


Another way would be to actually run it in a web environment with

flutter test --platform chrome

You can also add

@TestOn('browser')

at the top of your test file so your tests are only run when the platform is a browser.

Look at TestOn and its README.

like image 41
Valentin Vignal Avatar answered Aug 05 '26 10:08

Valentin Vignal