angular – 如何为Router Guard Jasmine测试模拟RouterStateSnap
发布时间:2020-12-17 07:33:00 所属栏目:安全 来源:网络整理
导读:我有一个简单的路由器防护,我正在尝试测试canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnapshot).我可以像这个新的ActivatedRouteSnapshot()一样创建ActivatedRouteSnapshot,但我无法弄清楚如何创建一个模拟的RouterStateSnapshot. 按照我试
我有一个简单的路由器防护,我正在尝试测试canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnapshot).我可以像这个新的ActivatedRouteSnapshot()一样创建ActivatedRouteSnapshot,但我无法弄清楚如何创建一个模拟的RouterStateSnapshot.
按照我试过的代码…… let createEmptyStateSnapshot = function( urlTree: UrlTree,rootComponent: Type<any>){ const emptyParams = {}; const emptyData = {}; const emptyQueryParams = {}; const fragment = ''; const activated = new ActivatedRouteSnapshot(); const state = new RouterStateSnapshot(new TreeNode<ActivatedRouteSnapshot>(activated,[])); return { state: state,activated: activated } } 但从“@ angular / router / src / utils / tree”导入{TreeNode};似乎需要进行转换或其他因为我得到……
我设法做的略有不同,但它应该适合你:
... let mockSnapshot:any = jasmine.createSpyObj<RouterStateSnapshot>("RouterStateSnapshot",['toString']); @Component({ template: '<router-outlet></router-outlet>' }) class RoutingComponent { } @Component({ template: '' }) class DummyComponent { } describe('Testing guard',() => { beforeEach(() => TestBed.configureTestingModule({ imports: [ RouterTestingModule.withRoutes([ {path: 'route1',component: DummyComponent},{path: 'route2',... ]) ],declarations: [DummyComponent,RoutingComponent],providers: [ GuardClass,{provide: RouterStateSnapshot,useValue: mockSnapshot} ] }).compileComponents()); it('should not allow user to overcome the guard for whatever reasons',inject([GuardClass],(guard:GuardClass) => { let fixture = TestBed.createComponent(RoutingComponent); expect(guard.canActivate(new ActivatedRouteSnapshot(),mockSnapshot)).toBe(false); }) ... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |