简体   繁体   中英

flutter: how to get the button widget in this flutter test?

I'm working with flutter test . I want to test something after tap a widget but I don't know how to find the button. Because I custom it rather than use Icon or iconButton . Also, I can't find it according to its text because another widget has the same name. And also two InkWell widget as you can see. My basic test code is here.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:grpc/grpc.dart';

import 'package:project/page/login.dart';

void main() {
  testWidgets('login page test', (WidgetTester tester) async {
    // Build our app and trigger a frame
    await tester.pumpWidget(Login());

    expect(find.text('login'), findsNWidgets(2));
    expect(find.text('ID'), findsOneWidget);
    expect(find.text('password'), findsOneWidget);
    expect(find.text('end'), findsOneWidget);

    // how to find my custom button
    await tester.tap((find.byElementType(InkWell)));  <- my question here

    // test other things after tapping the button.
  });

}

在此处输入图像描述

Instead of find.byElementType() use find.byType() .

So your code will be like this:

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

Like this you have to mention key (key: const Key("btnLogin"),)

ElevatedButton(
          key: const Key("btnLogin"),
          onPressed: () {
            _decrementCounter();
          },
          child: const Text(
            " Login ",
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.white),
          ),
        ),

in Widget test

await tester.tap(find.byKey(const Key('btnLogin')));
await tester.pump();
    InkWell(
          key: const Key("btnLogin"),
          child: ElevatedButton(
            onPressed: () {
              _decrementCounter();
            },
            child: const Text(
              " Login ",
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white),
            ),
          ),
        ),

Like this also we can do

await tester.tap(find.byKey(const Key('btnLogin')));
await tester.pump();

give a key name to your inkwell button like this.

- in your login screen.

     InkWell(
      key: const Key("login"),
      child: ElevatedButton(
        onPressed: () {
        },
        child: const Text(
          " Login ",
          textAlign: TextAlign.center,
          style: TextStyle(color: Colors.white),
        ),
      ),
    ),

 **- in your testing file**
    
   var loginButton = find.byKey(const Key('login'));
   await tester.tap(login);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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