简体   繁体   English

如何在 Flutter 小部件中测试回调 function

[英]How to test a callback function in a Flutter widget

I have a custom Flutter widget, RadioSelect, which accepts an array of options and a callback function when one of those options is pressed.我有一个自定义的 Flutter 小部件 RadioSelect,它接受一组选项,并在按下其中一个选项时返回一个回调 function。 The callback is called with the selected option passed as it's only parameter.调用回调时将选定的选项作为唯一参数传递。 I'm trying to write a test which verifies that the callback was called and checks that the returned parameter is correct but I'm not sure how to structure it.我正在尝试编写一个测试来验证是否调用了回调并检查返回的参数是否正确,但我不确定如何构造它。 What's a sensible way to check that a standalone callback function was called?检查是否调用了独立回调 function 的明智方法是什么?

  await tester.pumpWidget(
    StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        return MaterialApp(
          home:  RadioSelect(
                                ["option1","option2", "option3"], 
                                // callback function passed here
                                ),
            );
      },
    ),
  );

expect(find.text('option1'), findsOneWidget);

await tester.press(find.text('option2'));

await tester.pump();

// test for callback here

You can also use a Completer您还可以使用Completer

testWidgets('callback', (WidgetTester tester) async {
  final completer = Completer<void>();

  await tester.pumpWidget(
    MaterialApp(
      home: FlatButton(
        child: Text('press me'),
        onPressed: completer.complete,
      ),
    ),
  );

  await tester.tap(find.byType(FlatButton));

  expect(completer.isCompleted, isTrue);
});

source: https://luksza.org/2020/testing-flutter-callbacks/来源: https://luksza.org/2020/testing-flutter-callbacks/

In the body of a Callback function, you can print the received arguments, and then expect if it prints correctly.在 Callback function 的正文中,您可以打印收到的 arguments,然后期待它是否打印正确。

Here is another sample doing a similar test:这是另一个进行类似测试的示例:

CHILD OF A TESTING WIDGET:测试小工具的孩子:

...
...

Checkbox(
     key: Key('StatusCheckBox'),
     value: isCompleted,
     onChanged: (_) => toggleCompletionStatus(),
 ),

...
...

I'm passing print('Call') as a body of toggleCompletionStatus()我将print('Call')作为toggleCompletionStatus()的主体传递

Which can be tested this way:可以这样测试:

expectLater(
        () => tester.tap(find.byKey(Key('StatusCheckBox'))), prints('Call\n'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM