簡體   English   中英

Flutter:測試小部件

[英]Flutter: testing widgets

我正在嘗試測試的是:用戶點擊一個按鈕,小吃欄會顯示五秒鍾。

這是帶有鑰匙的腳手架:

final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(debugLabel: "scaffoldState");

...

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

然后是按鈕和小吃店的代碼:

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();

我不知道在里面放什么東西。 我試圖使用 find.ByKey(Key)) 獲取 GlobalKey 並搜索 debugLabel,但它似乎不起作用。 我已經嘗試了 2 天,但我找不到出路。

回答這個問題可能有點晚了,但由於這是在 Google 上輸入“Flutter test Snackbar”時的第二個結果,我只給我兩分錢:

其實很簡單。 不要認為 Snackbar 是完全不同的東西,因為它只在底部停留幾秒鍾。 最后,Snackbar 只是另一個 Widget。

記住這一點,您可以按如下方式進行測試:

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);
});

我實際上遇到了與您相同的條件,我所做的只是將文本作為小吃店的內容。

為了顯示小吃店,我使用的代碼是

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

我希望找到與我輸入的內容相同的文本,並添加 findsOneWidget。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM