如何模拟 RouterStateSnapshot 进行 Router Guard Jasmine 测试

2023-12-25

我有一个简单的路由器防护,我正在尝试测试canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot )。我可以像这样创建ActivatedRouteSnapshotnew 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
    }
}

But import {TreeNode} from "@angular/router/src/utils/tree";似乎需要进行转译或其他什么,因为我得到......

未捕获的语法错误:意外的令牌导出 在 webpack:///~/@angular/router/src/utils/tree.js:8:0


我设法做得略有不同,但它应该对你有用:

...

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', component: DummyComponent},
        ...
      ])
  ],
  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);
  })
 ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何模拟 RouterStateSnapshot 进行 Router Guard Jasmine 测试 的相关文章

随机推荐