我有一个简单的路由器防护,我正在尝试测试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};似乎需要进行转换或其他因为我得到……
Uncaught SyntaxError: Unexpected token export
at webpack:///~/@angular/router/src/utils/tree.js:8:0 <- test.bundle.ts:72431
我设法做的略有不同,但它应该适合你:
原文链接:https://www.f2er.com/angularjs/142345.html... 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); }) ...