颤振测试仪..tap无法正常工作。如何解决“状态错误:无元素”错误?

时间:2020-06-10 08:00:48

标签: flutter flutter-test

我正在Flutter应用中编写小部件测试。我可以使用键,文本或窗口小部件类型来找到按钮,但是当我点击它时,它将显示Bad State No element错误。下面是我的测试源代码。在allWidgets项下进行调试时,我还可以在tester对象中看到该元素。

class MockSpeechRecognizer extends Mock implements SpeechRecognizer {}

void main() {
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
  setUpAll(() {
    const MethodChannel('plugins.flutter.io/shared_preferences')
        .setMockMethodCallHandler((MethodCall methodCall) async {
      if (methodCall.method == 'getAll') {
        return <String, dynamic>{}; // set initial values here if desired
      }
      return null;
    });

    setupLocator();
  });
  group('DashboardView Test | ', () {
    testWidgets('Build Dashboard view and change keyword', (WidgetTester tester) async {
      final Preferences preferences=Preferences();
      preferences.keyword='hello';
      final MockSpeechRecognizer speechService = MockSpeechRecognizer();
      when(speechService.isServiceRunning).thenReturn(true);

      locator.unregister<SpeechRecognizer>();
      locator.registerLazySingleton<SpeechRecognizer>(() => speechService);

      locator<LocalStorageService>().setUserPreferences(preferences);

      // Build our app and trigger a frame.
      binding.window.physicalSizeTestValue = Size(600, 300);
      await tester.pumpWidget(MaterialApp(home:Dashboard()));

      await tester.pumpAndSettle();

      expect(find.byType(Dashboard),findsOneWidget);

      await tester.tap(find.byKey(const Key('ChangeKeyword')));
    });
  });
}


══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following StateError was thrown running a test:
Bad state: No element

When the exception was thrown, this was the stack:
#0      Iterable.single (dart:core/iterable.dart:554:25)
#1      WidgetController._getElementPoint (package:flutter_test/src/controller.dart:646:47)
#2      WidgetController.getCenter (package:flutter_test/src/controller.dart:618:12)
#3      WidgetController.tap (package:flutter_test/src/controller.dart:256:18)
#4      main.<anonymous closure>.<anonymous closure> (file:///E:/Siak/Meow/meow-phone-finder/test/Widgets/dashboardView_test.dart:52:20)
<asynchronous suspension>
#5      main.<anonymous closure>.<anonymous closure> (file:///E:/Siak/Meow/meow-phone-finder/test/Widgets/dashboardView_test.dart)
#6      testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:140:29)
<asynchronous suspension>
#7      testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart

below is the result when i called debugDumpApp()

1 个答案:

答案 0 :(得分:0)

您在哪里定义按钮,是否设置了Key参数?

await tester.pumpWidget(MaterialApp(home: 
  Container(child: 
    Button(
      key: Key("ChangeKeyword"),
      onTap: () => {},
      child: Text("Press me"),
    ),
  ),
));