Ngrx effects testing - how to test auth login

Viewed 735

Sorry to bother you but I've a hard time to

understand the logic behind testing effects :(

Can anyone show and explain me a little bit

how to test this Auth login Effects?

I'm also looking for some useful tutorial :)

AuthEffects

import { Injectable } from '@angular/core';

import { of } from 'rxjs';
import { map, switchMap, catchError } from 'rxjs/operators';

import { Actions, Effect, ofType } from '@ngrx/effects';

import { Credentials, AuthToken } from '../../models';
import { Go } from '../../../router';
import { AuthService } from '../../services';
import { AuthActionTypes, Login, LoginFailure, LoginSuccess } from '../actions';

@Injectable()
export class AuthEffects {
  @Effect()
  login$ = this.actions$.pipe(
    ofType(AuthActionTypes.Login),
    map((action: Login) => action.payload.credentials),
    switchMap((credentials: Credentials) => {
      return this.service.login(credentials).pipe(
        map((token: AuthToken) => new LoginSuccess({ token })),
        catchError(error => of(new LoginFailure(error)))
      );
    })
  );

  @Effect()
  loginSuccess$ = this.actions$.pipe(
    ofType(AuthActionTypes.LoginSuccess),
    map(() => new Go({ path: ['/admin'] }))
  );

  constructor(private actions$: Actions, private service: AuthService) {}
}

AuthEffects Testing

// Testing
import { HttpClientTestingModule } from "@angular/common/http/testing";
import { TestBed } from "@angular/core/testing";
import { provideMockActions } from "@ngrx/effects/testing";

// Rxjs
import { Observable } from "rxjs";

// Marbles
import { hot, cold } from "jasmine-marbles";

// Store
import { Credentials, AuthToken } from "../../models";
import { CONFIG, Config } from "../../../../config/config.module";
import { AuthService } from "../../services";
import { AuthEffects } from "./auth.effects";
import * as fromActions from "../actions";

const credentials: Credentials = {
  email: "io@io.io",
  password: "abc"
};
const error: any = { status: 401, message: "401 Unauthorized Error" };
const token: AuthToken = {
  token: "abc",
  expiresIn: 1546356028904
};

describe("AuthEffects", () => {
  let effects: AuthEffects;
  let actions: Observable<any>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        AuthService,
        {
          provide: CONFIG,
          useClass: Config
        },
        AuthEffects,
        provideMockActions(() => actions)
      ]
    });

    effects = TestBed.get(AuthEffects);
  });

  it("should work", () => {
    const action = new fromActions.Login({ credentials });
    const completion = new fromActions.LoginSuccess({ token });


    actions = hot("a", { a: action });
    const expected = cold("b", { b: completion });

    expect(effects.login$).toBeObservable(expected);
  });
});

The test fails with the message

Error: Expected $.length = 0 to equal 1.
1 Answers
Related