flutter 在小部件测试的上下文中未找到GoRouter

unhi4e5o  于 2023-01-27  发布在  Flutter
关注(0)|答案(1)|浏览(263)

我尝试在我的小部件测试中模拟go_router,但总是得到这个错误:

══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
No GoRouter found in context
'package:go_router/src/router.dart':
Failed assertion: line 300 pos 12: 'inherited != null'

When the exception was thrown, this was the stack:
#2      GoRouter.of (package:go_router/src/router.dart:300:12)
#3      GoRouterHelper.pushNamed (package:go_router/src/misc/extensions.dart:50:16)
#4      _ProfileEditWidgetState._getSubmitButton.<anonymous closure>.<anonymous closure> (package:app/widgets/profile/profile_edit_widget.dart:236:33)

我使用的是go_router 6.0.0
下面是我的测试结果:

final router = MockGoRouter();
when(router.pushNamed(any)).thenReturn(null);

await tester.pumpWidget(
      MultiProvider(
        providers: [
          BlocProvider<ProfileBloc>(create: (context) => profileBloc),
        ],
        child: MaterialApp(
          locale: const Locale("en"),
          home: InheritedGoRouter(
            goRouter: router,
            child: ProfileEditWidget(),
          ),
        ),
      ),
    );

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

在我的个人资料编辑小部件中的提交按钮上按下这是我有:

context.pushNamed(
    VERIFY_PHONE,
     queryParams: {
         'updatedPhone': phone
      },
)

似乎也没有关于go的文档来处理使用go路由器的测试

pcww981p

pcww981p1#

尝试将MaterialApp更改为MaterialApp.router
并使用GoRouter()代替MockGoRouter()

import 'package:go_router/go_router.dart';

// GoRouter configuration
final _router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => HomeScreen(),
    ),
  ],
);
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: _router,
    );
  }
}

相关问题