How do I Mock RouterStateSnapshot for a Router Guard Jasmine test

后端 未结 4 1081
生来不讨喜
生来不讨喜 2021-02-05 05:23

I have a simple router guard and I am trying to test the canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ). I can create the ActivatedRouteSn

4条回答
  •  再見小時候
    2021-02-05 05:50

    If the purpose is just to pass the mock to the guard, it's not necessary to use createSpyObj, as suggested in other answers. The simplest solution is just to mock only required fields, which are used by canActivate method of your guard. Also, it would be better to add type safety to the solution:

    const mock = (obj: Pick): T => obj as T;
    
    it('should call foo', () => {
        const route = mock({
            params: {
                val: '1234'
            }
        });
    
        const state = mock({
            url: "my/super/url",
            root: route // or another mock, if required
        });
    
        const guard = createTheGuard();
        const result = guard.canActivate(route, state);
        ...
    });
    

    If you don't use the state snapshot, just pass null instead

        const result = guard.canActivate(route, null as any);
    

提交回复
热议问题