简体   繁体   中英

How do I unit test canActivate of Angular for authguard?

How do I perform unit testing for auth guard?

I don't know how to start, can anyone please help me?

This is my authguard.component:

import { Injectable } from '@angular/core';
import {
  Router,
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';

import { LoginService } from '../services/login/login.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router, private loginService: LoginService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const currentUser = this.loginService.currentUserValue;
    if (currentUser) {
      // Authorized so return true
      return !0;
    }

    // not authorized so redirect to signin page with the return url
    this.router.navigate(['/login'], {
      queryParams: { returnUrl: state.url }
    });
    return !1;
  }
}

You need mocks for the Router and the LoginService.

A test might look like this:

describe('LoginService', () => {
let navigateMock;
let loginService: LoginService;

beforeEach(() => {
    navigateMock = jest.fn();
    const RouterMock: Mock<Router> = jest.fn(() => (<Router> {
         navigate: navigateMock,
    }));
    // ...some more mocks
}

it('should redirect without error', (done: DoneCallback) => {
     // mock the login method, e.g. 
    loginServiceMock.loadDocumentAndLogin = jest.fn(() => Promise.reject({} as OAuthErrorEvent)); // if you use OAuth

     // call loginService.canActivate and expect the behaviour of the navigator    
     loginService.canActivate().subscribe(f => f, () => {
          expect(navigateMock).toBeCalledWith(['loginerror'], {
          queryParams: {
               code: '',
               description: ''
          }
          });
          done();
          });
     });

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM