I am currently writing a test for the following dispatch event:
@Injectable()
export class AuthEffects {
signIn$ = createEffect(() =>
this.actions$.pipe(
ofType(AuthActions.signIn),
switchMap((action) =>
from(this.loginService.signIn(action.email, action.password, action.redirectTo)).pipe(
map(() => AuthActions.signInSuccess()),
catchError((err: Error) =>
of(
AuthActions.signInError({
message: err.message,
})
)
)
)
)
)
);
constructor(
private actions$: Actions,
private loginService: LoginService
) {}
}
The test is as follows:
describe('AuthEffects', () => {
let effects: AuthEffects;
let actions$: Observable<Action>;
let mockLoginService: LoginService;
let mockSupabaseService: SupabaseService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideMockActions(() => actions$), AuthEffects],
});
effects = TestBed.inject(AuthEffects);
mockLoginService = TestBed.inject(LoginService);
mockSupabaseService = TestBed.inject(SupabaseService);
});
describe('signIn$', () => {
it('should allow sign in', () => {
const payload = { email: '[email protected]', password: '123', redirectTo: 'dashboard' };
actions$ = cold('a', { a: AuthActions.signIn(payload) });
jest.spyOn(mockSupabaseService, 'signIn').mockImplementation(() => Promise.resolve([]));
effects.signIn$.subscribe(() => {
expect(mockLoginService.signIn).toHaveBeenCalled();
});
});
it('should not allow sign in', () => {
const payload = { email: '[email protected]', password: '123', redirectTo: 'dashboard' };
const mockError = { name: 'test', message: 'test' };
actions$ = cold('a', { a: AuthActions.signIn(payload) });
jest.spyOn(mockSupabaseService, 'signIn').mockImplementation(() => {
return Promise.reject(mockError);
});
effects.signIn$.subscribe(() => {
expect(mockLoginService.signIn).toHaveBeenCalled();
});
});
});
});
I am having issues with mocking the output required to reach coverage on the catchError
method. Everytime I run the test, I get the following error:
console.error
Unhandled Promise rejection: { name: 'test', message: 'test' } ; Zone: ProxyZone ; Task: null ; Value: { name: 'test', message: 'test' } undefined
How do I fix this?
Have your signIn
mock call the rxjs throwError
operator:
jest.spyOn(mockSupabaseService, 'signIn').mockImplementation(() => throwError(mockError));