Flutter - 从 Widget 测试/UI 测试中单击部分 RichText(特定 TextSpan)

问题描述 投票:0回答:1

假设您需要在运行 Widget UI 测试的 Flutter widget 树中单击以下

TextSpan
斜体文本范围

用户界面如下所示:

RichText(
  key: Key("anyKey"),
  textAlign: TextAlign.center,
  text: TextSpan(
    text: "This is a heading\n",
    children: <TextSpan>[
      TextSpan(
        text: "Text span in bold",
        recognizer: TapGestureRecognizer()
          ..onTap = () {
            ref.read(sampleServiceProvider).open(Urls.url1);
          },
      ),
      TextSpan(text: " and "),
      TextSpan(
        text: "Text span in italic",
        recognizer: TapGestureRecognizer()
          ..onTap = () {
            ref.read(sampleActionProvider).actionOne();
          },
      ),
    ],
  ),
)

如何区分 Flutter 中 RichText 小部件内的

TextSpan
点击?

flutter integration-testing richtext
1个回答
0
投票

使用以下代码单击小组件测试中的特定 TextSpan:

RichText richText = ($.widgetByKey(const Key("anyKey")) as RichText);
richText.click("Text span in italic");

具有以下扩展:

/// Enables Widget tests to click on a specific text INSIDE text spans/rich texts
extension TextSpanHelper on RichText {
   void click(String innerText) {
      text.visitChildren((span) {
        if (span.toPlainText() == innerText) {
          ((span as TextSpan).recognizer as TapGestureRecognizer).onTap?.call();
          return false;
        }
        return true;
      });
   }
}

T widget<T extends Widget>() => tester.widget(find.byType(T));
Iterable<T> widgetList<T extends Widget>() => tester.widgetList(find.byType(T));
Widget widgetByKey(Key key) => tester.widget(find.byKey(key));
使用

LeanCode Patrol

© www.soinside.com 2019 - 2024. All rights reserved.