Search code examples
flutterbloc-test

Why state is not updating in bloc_test?


I am new at testing of flutter app, so I am trying to find out how to test it correctly, and now I am confused when I faced this error. When I try to change state in bloc_state testing then state doesn't change at all. So how can I fix that?

class MockAuth extends MockBloc<AuthCubit, AuthState> implements AuthCubit {}

void main() {
  blocTest(
    build: () => MockAuth(), // If I change MockAuth to AuthCubit then it starts to work
    act: (bloc) async {
      bloc.setEmail("[email protected]");
    },
    expect: () => [
      AuthState(
        email: "[email protected]",
        password: "",
        firstName: "",
        lastName: ""
        ...
      )
    ]
  );
}

This is my cubit:

class AuthCubit extends Cubit<AuthState> {
  AuthCubit() : super(const AuthState(
    email: "",
    password: "",
    firstName: "",
    lastName: "",
    genderUuid: "",
    ageGroupUuid: "",
    countryUuid: "",

    forgotEmail: "",
    code: 0,

  ));

  void setEmail(String email) => emit(state.copyWith(email: email));
}

Solution

  • I guess you were following the bloc_test documentation which is great but can be confusing. For this case scenario, you don't want to mock your bloc/cubit, since you want to test its actual behavior and logic. So, on the build parameter, you pass the blocTest a real instance of your bloc/cubit, and on the act parameter, you add/invoke an event/method to your bloc/cubit, then expect the bloc to emit different states.

    In case any of your cubit methods depends on a repository request or any other service, you should mock that repository/service to get the expected result and the expected state emitted.

    But this is not the case, so your test should look something like this:

    blocTest<AuthCubit, AuthState>(
        build: () => AuthCubit(),
        act: (bloc) async {
          bloc.setEmail("[email protected]");
        },
        expect: () => [
          AuthState(
            email: "[email protected]",
            password: "",
            firstName: "",
            lastName: ""
            ...
          )
        ]
      );