如何为Router Guard Jasmine测试模拟RouterStateSnapshot

Jac*_*kie 17 jasmine angular2-routing angular

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

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

未捕获的SyntaxError:webpack上的意外的令牌导出:///~/@angular/router/src/utils/tree.js:8:0 < - test.bundle.ts:72431

小智 11

我设法做了稍微不同但它应该适合你:

...

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);
  })
 ...
Run Code Online (Sandbox Code Playgroud)


ram*_*n22 7

我需要获取路由中的数据来测试我的后卫中的用户角色,所以我这样嘲笑它:

class MockActivatedRouteSnapshot {
    private _data: any;
    get data(){
       return this._data;
    }
}

describe('Auth Guard', () => {
   let guard: AuthGuard;
   let route: ActivatedRouteSnapshot;

   beforeEach(() => {
      TestBed.configureTestingModule({
         providers: [AuthGuard, {
            provide: ActivatedRouteSnapshot,
            useClass: MockActivatedRouteSnapshot
        }]
      });
      guard = TestBed.get(AuthGuard);
  });

  it('should return false if the user is not admin', () => {
     const expected = cold('(a|)', {a: false});

     route = TestBed.get(ActivatedRouteSnapshot);
     spyOnProperty(route, 'data', 'get').and.returnValue({roles: ['admin']});

     expect(guard.canActivate(route)).toBeObservable(expected);
  });
});
Run Code Online (Sandbox Code Playgroud)


Val*_*kov 6

如果目的只是将模拟传递给警卫,则无需使用createSpyObj,如其他答案中所建议的那样。最简单的解决方案就是仅模拟所需的字段,这些字段由canActivate您的守卫方法使用。另外,最好在解决方案中添加类型安全:

const mock = <T, P extends keyof T>(obj: Pick<T, P>): T => obj as T;

it('should call foo', () => {
    const route = mock<ActivatedRouteSnapshot, 'params'>({
        params: {
            val: '1234'
        }
    });

    const state = mock<RouterStateSnapshot, "url" | "root">({
        url: "my/super/url",
        root: route // or another mock, if required
    });

    const guard = createTheGuard();
    const result = guard.canActivate(route, state);
    ...
});
Run Code Online (Sandbox Code Playgroud)

如果不使用状态快照,则直接传递null即可

    const result = guard.canActivate(route, null as any);
Run Code Online (Sandbox Code Playgroud)


Jac*_*kie 2

根据我之前关于路由器的问题,我尝试了这个......

let mockSnapshot: any;
...
mockSnapshot = jasmine.createSpyObj("RouterStateSnapshot", ['toString']);
...
TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  providers:[
    {provide: RouterStateSnapshot, useValue: mockSnapshot}
  ]
}).compileComponents();
...
let test = guard.canActivate(
  new ActivatedRouteSnapshot(),
  TestBed.get(RouterStateSnapshot)
);
Run Code Online (Sandbox Code Playgroud)

我现在遇到的问题是我需要这里的 toString mockSnapshot = jasmine.createSpyObj("RouterStateSnapshot", ['toString']);。这是因为 jasmine createSpyObj 需要至少一种模拟方法。由于我没有测试 RouterStateSnapshot 的副作用,因此这似乎是徒劳的额外工作。