Flutter:测试小部件

3
我正在尝试测试的是:用户点击一个按钮,然后Snackbar会显示五秒钟。 这是带有其关键内容的Scaffold:
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(debugLabel: "scaffoldState");

...

builder: (context, viewModel) => Scaffold(
              key: _scaffoldKey,

然后是按钮和 snackBar 的代码:

child: FlatButton(key: Key('loginButton'), onPressed: () { 
 validate();

...

  validate() {
    // FormState object can be used to save, reset, and validate
    // every FormField that is a descendant of the associated Form.

    final FormState form = _formKey.currentState;

    if (form.validate()) {
      form.save();
      form.reset();

      //implementation of the snackBar:
      _scaffoldKey.currentState.showSnackBar(new SnackBar(
        duration: new Duration(seconds: 5)

我正试图通过以下方式测试这种行为(我也在使用Flutter redux):

void main(){

  final store = Store<AppState>(reducer, initialState: AppState.initialState());
  testWidgets("MaterialApp local", (WidgetTester tester) async{
    await tester.pumpWidget(new StoreProvider(
        store: store,
        child: MaterialApp(
          home: LoginView(),
        )));
    await tester.pumpAndSettle();
    await tester.press(find.byKey(Key("loginButton")));
    expect();

我不知道应该在expect里面放什么。我试着使用find.byKey(Key)来获取GlobalKey并搜索debugLabel,但似乎不起作用。我已经尝试了两天,但是还是找不到解决方法。

2个回答

1

可能有点晚回答了,但是因为在谷歌上输入“Flutter test Snackbar”时它是第二个结果,所以我想说两句:

其实很简单。不要认为Snackbar只是因为它只在底部停留几秒钟而完全不同。最后,Snackbar只是另一个小部件。

记住这一点,您可以按以下方式测试它:

testWidgets("MaterialApp local", (WidgetTester tester) async{
  ...
  // Test if the Snackbar appears
  expect(find.byType(SnackBar), findsOneWidget);
  // Test if it contains your text
  expect(find.text('TAPS!'), findsOneWidget);
});


0

我曾经遇到和你一样的情况,解决方法很简单,只需要将文本作为 snackbar 的内容即可。

我使用的代码来显示 snackbar 如下:

scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("TAPS!"),));
          }, "SEE ALL", backgroundColor: Colors.red, textColor: Colors.blue)

我期望找到与我输入的相同内容的文本,并添加findsOneWidget。

expect(find.text("TAPS!"), findsOneWidget);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接