I am trying to do a very simple blocTest to test initial state. But getting below error. Interestingly I do have another working bloc and test in the same project. I checked line by line to see any mismatch, but everything looks perfect, except the 'act', which I am doing in the other, not here, assuming not relevant for this initial state test. Any idea, why this is happening to this bloc?
Expected: [ReadyToAuthenticateState:ReadyToAuthenticateState()]
Actual: []
Which: at location [0] is [] which shorter than expected
My bloc test
late MockUserAuthenticationUseCase mockUsecase;
late UserAuthenticationBloc authBloc;
setUp(() {
mockUsecase = MockUserAuthenticationUseCase();
authBloc = UserAuthenticationBloc(usecase: mockUsecase);
});
blocTest<UserAuthenticationBloc, UserAuthenticationState>(
'emits [MyState] when MyEvent is added.',
build: () => authBloc,
expect: () => <UserAuthenticationState>[ReadyToAuthenticateState()],
);
My bloc
class UserAuthenticationBloc
extends Bloc<UserAuthenticationEvent, UserAuthenticationState> {
final UserAuthenticationUseCase usecase;
UserAuthenticationBloc({required this.usecase})
: super(ReadyToAuthenticateState()) {
on<UserAuthenticationEvent>((event, emit) {
if (event is AuthenticateUserWithCredentialsEvent) {
_processReadyToAuthenticateEvent(event);
}
});
}
void _processReadyToAuthenticateEvent(
AuthenticateUserWithCredentialsEvent event) async {
await usecase(
UserAuthenticationUseCaseParams(event.username, event.password));
}
}
Update #1: I inserted initial state expectation also to the other working blocTest and got the same error. Seems we are not expected to test initial state.
CodePudding user response:
This is the expect
property documentation in bloc_test
package:
/// [expect] is an optional `Function` that returns a `Matcher` which the `bloc`
/// under test is expected to emit after [act] is executed.
Meaning, inside the expect
callback, you should put only the emitted states. Initial state is, well, the initial one, it is not emitted after you add an event to the BLoC.
If you want to verify an initial state of the BLoC, you can write a separate test for it:
test('should set initial state', () {
expect(authBloc.state, ReadyToAuthenticateState());
});