vendredi 11 octobre 2019

How to test a widget created by void function in flutter?

I'm trying to test a showDialog Widget from following function:

void handleResponseCode(String code, BuildContext context) async {
  String respond;
  Map<String, String> responses = {
    '200': 'Connection successful',
    '401': 'Invalid or no API key found',
    '403': 'Your API access isn\'t enabled.',
    '500': 'We hit a server error.'
  };
  responses.containsKey(code)
      ? respond = responses[code]
      : respond = 'Unknown error accured during connection.';
  AlertDialog alert = AlertDialog(
    title: code == '200'
        ? Text('Success', style: TextStyle(color: Colors.green))
        : Text('Connection error', style: TextStyle(color: Colors.red)),
    content: Text(respond),
    actions: <Widget>[
      FlatButton(
        child: Text('OK'),
        onPressed: Navigator.of(context).pop,
      )
    ],
  );
  showDialog(context: context, builder: (BuildContext context) => alert);
}

With a following test:

main() {
  group('Handling different response code', () {
    testWidgets('200 OK', (WidgetTester tester) async {
      await tester.pumpWidget(Builder(
          builder: (BuildContext context) =>
              handleResponseCode('200', context)));
    });
  });
}

Screen version

There are two main problems i have with testing it.

  1. Because of context parameter i need to use Builder which requires a Widget annonymous closure as a builder: (as seen on screen).
  2. The function returns void and tester.pumpWidget method that I tried to use requires a Widget object and I cant simply return a Widget because showDialog returns Future<Widget> that is not allowed in Builder constructor.

I want to create this Widget somehow and by using finder test it or change the function in a way that it will return my showDialog as a Widget and not Future (but I believe it's impossible).

Aucun commentaire:

Enregistrer un commentaire