Monday, 7 January 2019

Ngrx how to test a guard

I want to test this simple guard both canActivate and canLoad How can manage it ? I did my first step manage the injected store

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanLoad {
    constructor(private store: Store<AuthState>) {}

    canActivate(): Observable<boolean> {
        return this.store.pipe(
            select(selectIsAuthenticated),
            map(isValidToken => {
                if (!isValidToken) {
                    this.store.dispatch(new Logout());
                    return false;
                }
                return true;
            }),
         take(1)
       );
    }

    canLoad(): Observable<boolean> {
        return this.store.pipe(
            select(selectIsAuthenticated),
            map(isValidToken => {
                if (!isValidToken) {
                    this.store.dispatch(new Logout());
                    return false;
                }
                return true;
            }),
            take(1)
        );
    }
}

My first step

export const authReducer: ActionReducerMap<{}> = {
  status: {}
};
describe('AuthGuard', () => {
  let store: Store<{}>;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [StoreModule.forRoot({}).forFeature('auth', authReducer)],
      providers: [Store, AuthGuard]
    });
    store = TestBed.get(Store);
  });

  it('should ...', inject([AuthGuard], (guard: AuthGuard) => {
    expect(guard).toBeTruthy();
  }));
});

But what about testing canActivate and canLoad ? I've to mock the select and how ?



from Ngrx how to test a guard

No comments:

Post a Comment