I am writing a widget test for a button widget, but the text part can not be tested successfully.
Here is the widget testing code:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:ui_widgets/src/modules/buttons/elevated_button.dart';
void main() {
testWidgets('Button testing', (WidgetTester tester) async {
await tester.pumpWidget(
const Material(
child: ElevatedButton(
buttonText: 'button text',
),
),
);
await tester.pump();
expect(find.text('button text'), findsOneWidget);
});
}
Here is the Error log:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following ProviderNotFoundException was thrown building ElevatedButton(dirty):
Error: Could not find the correct Provider<AppTheme> above this ElevatedButton Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that ElevatedButton is under your MultiProvider/Provider<AppTheme>.
This usually happens when you are creating a provider and trying to read it immediately.
Q1: How to deal with this exception?
Q2: ow to test on other widget function of the button (i.e. onPress function)?
(Expect a bug-free code can pass the test. Thanks!)