简体   繁体   English

如何为此 canActivate Guard 进行单元测试

[英]How can I make a Unit test for this canActivate Guard

here's the big deal how can I do a Unit test for this Guard, The purpose of this is if I am authenticated, then return false and redirect to login and if we return to login and if we have authenticaded before then go to profile page if it's our first time that we're logging then go forward, why?这是我如何为这个 Guard 进行单元测试的大问题,这样做的目的是如果我通过了身份验证,然后返回 false 并重定向到登录,如果我们返回登录并且如果我们之前已经过身份验证,那么 go 到配置文件页面如果这是我们第一次记录然后 go 向前,为什么? cause I do not want go to that route (callback page) in this case that route its a callback from an external service (okta) this is the code of guard:因为我不希望 go 到该路由(回调页面),在这种情况下,从外部服务(okta)路由它的回调这是守卫的代码:

import { Injectable } from '@angular/core';
import { LoginMineService } from '../login/login-mine.service';
import { Router } from '@angular/router';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class LoginCheckGuard implements CanActivate {

  constructor(private loginMineService: LoginMineService,
              private router: Router,
  ) {

  }
  canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (!this.loginMineService.isAuthenticated) {
      return true;

    } else {
      this.router.navigate(['/login']);
      return false;

    }

  }
}

and this is the Unit test code:这是单元测试代码:

import { TestBed } from '@angular/core/testing';

import { LoginCheckGuard } from './login-check.guard';

describe('LoginCheckGuard', () => {
  let guard: LoginCheckGuard;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    guard = TestBed.inject(LoginCheckGuard);
  });

  it('should be created', () => {
    expect(guard).toBeTruthy();
  });



});

PS: I am working on Angular 9, Thank y'all PS:我正在研究 Angular 9,谢谢大家

Something like this should work:像这样的东西应该工作:

import { TestBed } from '@angular/core/testing';

import { LoginCheckGuard } from './login-check.guard';
.......

describe('LoginCheckGuard', () => {
  let guard: LoginCheckGuard;
  let mockLoginMineService = { isAuthenticated: undefined };
  let loginMineservice: LoginMineService;
  let router: Router;

  beforeEach(() => {    
    TestBed.configureTestingModule({ 
      // RouterTestingModule to get a handle on the router in a testing environment
      imports: [RouterTestingModule],
      providers: [
                  LoginCheckGuard,
        { provide: LoginMineService, useValue: mockLoginMineService },
      ],
    });
    // get handle on items that are needed
    guard = TestBed.inject(LoginCheckGuard);
    loginMineService = TestBed.inject(LoginMineService);
    router = TestBed.inject(router);
    // spy on the router navigate
    spyOn(router, 'navigate');
  });

  it('should be created', () => {
    expect(guard).toBeTruthy();
  });

  it('should return true if the user isAuthenticated', () => {
    loginMineService.isAuthenticated = true;
    expect(guard.canActivate()).toBe(true);
  });

  it('should return false if the user is not authenticated and navigate to login', () => {
     loginMineService.isAuthenticated = false;
     expect(guard.canActivate()).toBe(true);
     expect(router.navigate).toHaveBeenCalledWith(['/login']);
  });
});

Keep in mind I did this without a code editor so there might be some typos.请记住,我在没有代码编辑器的情况下执行此操作,因此可能会有一些拼写错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 canActivate 保护为 angular 路由编写单元测试 - How to write a unit test for angular routing with canActivate guard 如何制作依赖于 2 个 http 调用完成的 canActivate 防护? - How do I make a canActivate guard that depends on 2 http calls finishing? 如何使用 Angular 管理我的导航栏可以激活保护 - how can I manage my Navbar using Angular canactivate guard 如何使用 Jasmine 对 angular2 的 canActivate 防护方法进行单元测试? - How to unit-test canActivate guard method of angular2 using Jasmine? 如何对Angular的canActivate进行单元测试? - How to unit test canActivate of Angular? 如何对 Resolve 和 CanActivate 进行单元测试 - How to unit test Resolve and CanActivate 如何为authguard单元测试canActivate of Angular? - How do I unit test canActivate of Angular for authguard? 如何禁用 canActivate 防护 - How to disable canActivate guard 如何在 Angular 9 中实现 CanActivate 的警卫中使用 http 请求的结果? - How can I use the result of an http request in a guard implementing CanActivate in Angular 9? 如何防止 canActivate 在 Angular 防护的构造函数中完成 ReplaySubject 之前执行? - How can I prevent canActivate from executing before a ReplaySubject finished in the constructor of the Angular guard?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM