【问题标题】:Flutter Test only works with pumping duration颤振测试仅适用于泵送持续时间
【发布时间】:2021-10-23 08:42:15
【问题描述】:

我有这个小部件:

class _DemoWidget extends State<DemoWidget> {
  Choices? _selectedChoice;

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          createTile(
              'The First Option', Choices.FRIENDS, const Key('firstOption')),
          if (_selectedChoice == Choices.FIRST)
            TextFormField(
              key: const Key('searchFirst'),
            ),
          createTile('The Second Option', Choices.CONTACT, const Key('secondOption')),
          if (_selectedChoice == Choices.SECOND)
            TextFormField(
              key: const Key('searchSecond'),
            ),
        ],
      ),
    );
  }

  RadioListTile<Choices> createTile(String title, Choices choice, Key key) {
    return RadioListTile<Choices>(
      key: key,
      title: Text(
        title,
      ),
      value: choice,
      groupValue: _selectedChoice,
      onChanged: (Choices? val) => setState(() => _selectedChoice = val),
    );
  }
}

它有两个单选按钮,根据当前处于活动状态的按钮,它将在该选项下方呈现一个文本字段。我正在尝试为此行为创建测试并从以下开始:

  testWidgets('Clicking on person search opens up textfield',
      (WidgetTester tester) async {
    await tester.pumpWidget(
      renderWith(),
    );
    Finder firstOption = find.text('The First Option');
    await tester.tap(firstOption);
    expect(find.byKey(const Key('searchFirst')), findsOneWidget);
  }, skip: false);

但每次测试都会失败,然后我在点击和确保可见之间添加了一个持续时间

  testWidgets('Clicking on person search opens up textfield',
      (WidgetTester tester) async {
    await tester.pumpWidget(
      renderWith(),
    );
    Finder firstOption = find.text('The First Option');
    await tester.tap(firstOption);
    await tester.pump(Duration(milliseconds: 50));
    tester.ensureVisible(find.byKey(const Key('searchFirst')));
    expect(find.byKey(const Key('searchFirst')), findsOneWidget);
  }, skip: false);

测试通过了。

我认为使用超时似乎不是一种非常安全的测试方式,但在某些地方已经读到某些颤振小部件需要这样做。有没有什么方法可以做这个测试,而不必在测试器中等待时间?

【问题讨论】:

    标签: flutter dart testing


    【解决方案1】:

    According to Flutter documentation,你只需要使用pump

    Finder firstOption = find.text('The First Option');
    await tester.tap(firstOption);
    await tester.pump();
    

    【讨论】:

    • 哇,我在文档中忽略了这一点,非常感谢!我有很多与此类似的边缘情况,但没有意识到有时这是必需的。
    猜你喜欢
    • 2022-12-12
    • 2019-01-28
    • 2020-01-28
    • 2021-01-17
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2021-10-22
    相关资源
    最近更新 更多