0

I want to test my ViewModel that goes to a named route with GoRouter. Therefore, I pass my context from my View to the ViewModel. My problem is that the mocked contains does not contain a GoRouter. I get the error "No GoRouter found in context". How do I mock the context so that I can unit test this?

void main() {
    group("MainScreenViewModel Tests", () {
    MainScreenViewModel viewModel = MainScreenViewModel();

    setUp(() {
        viewModel = MainScreenViewModel();
    });

    test("MoveToTab should change currentIndex value", () {
        final context = MockBuildContext();

        when(() => context.goNamed("Test")).thenReturn(null); // Here is the problem

        viewModel.moveToTab(context, index: 1);
        expect(viewModel.currentIndex, 1);
        verify(() => context.goNamed(any())).called(1);
        verify(() => notifyListenerCallback()).called(1);
        });
    });
}

The ViewModel

const List<String> routeList = ["/a", "/b"];

class MainScreenViewModel extends ChangeNotifier {
int _currentIndex = 0;

int get currentIndex => _currentIndex;

void moveToTab(BuildContext context, {required int index}) {
    _currentIndex = index;
    context.goNamed(routeList[index]);
    notifyListeners();
}

}

maxmitz
  • 258
  • 1
  • 4
  • 17

0 Answers0