Sunday, 4 August 2019

How test angular guards/resolvers without mocking ActivatedRouteSnapshot

I'm trying to test an Angular Resolver which accessing children routes param.

My guard is working fine but I cannot create an unit test easily because I cannot create an ActivatedRouteSnapshot with children routes (read only property).

My resolver

@Injectable({
    providedIn: 'root'
})
export class MyResolverGuard implements Resolve<string> {

    constructor() {
    }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): string {
        return route.firstChild.paramMap.get('my-param');
    }
}


My test :

    it('should resolve chilren route params', () => {
        guard = TestBed.get(MyResolverGuard);
        const route = new ActivatedRouteSnapshot();
        // Cannot assign children because it's a read only property
        route.children = [...];
        const myResolverParams = guard.resolve(route, null);
    });

Is there other ways other than mock ActivatedRouteSnapshot ?

Does my approach to test guard is good ?

Thanks for sharing your strategy.



from How test angular guards/resolvers without mocking ActivatedRouteSnapshot

No comments:

Post a Comment