jeudi 18 juillet 2019

Flutter: How to test the dynamic color of a Widget using testWidgets

I want to write unit tests for a custom Widget, specifically check the color of a nested Text Widget that is themed based on BuildContext. How do I test for different styles based on the BuildContext?

The Widget to test:

class ThemedText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final TextStyle inheritedTextStyle = Theme.of(context).textTheme.subtitle;
    Color customColor = inheritedTextStyle.color;
    if (inheritedTextStyle.color == Colors.blue) {
      // Override the inherited color
      customColor = Colors.red;
    }

    return Text(
      'Themed',
      style: inheritedTextStyle.copyWith(color: customColor),
    );
  }
} 

I want to write two tests: - Supply an inherited TextStyle with a color that is Colors.blue, and test whether the Text Widget is rendered with the overriden color (i.e. Colors.blue). - Supply an inherited TextStyle with a color that is NOT Colors.blue (e.g. Colors.green), and test whether the Text Widget is rendered with the inherited color (e.g. Colors.green).

Aucun commentaire:

Enregistrer un commentaire