Skip to content

Instantly share code, notes, and snippets.

@rossholdway
Last active May 19, 2020 20:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossholdway/89a50d466d55bbed8d402c2d81f44741 to your computer and use it in GitHub Desktop.
Save rossholdway/89a50d466d55bbed8d402c2d81f44741 to your computer and use it in GitHub Desktop.
Stub Angular 2+ routers activatedRoute.
import {
DefaultUrlSerializer,
convertToParamMap,
ParamMap,
Params,
UrlSegment,
UrlSegmentGroup,
PRIMARY_OUTLET
} from '@angular/router';
import { ReplaySubject } from 'rxjs';
/**
* An ActivateRoute test double with `paramMap` and 'url' observables.
* @example
* // Sets url to categories/featured and param map to slug: 'featured'.
* const route = new ActivatedRouteStub();
* route.set('categories/:slug', {slug: 'featured'});
*/
export class ActivatedRouteStub {
// Use a ReplaySubject to share previous values with subscribers
// and pump new values into the `paramMap` and 'url' observables
private paramMapSubject = new ReplaySubject<ParamMap>();
private urlSubject = new ReplaySubject<UrlSegment[]>();
constructor() {}
/** The mock paramMap observable */
readonly paramMap = this.paramMapSubject.asObservable();
/** The mock url observable */
readonly url = this.urlSubject.asObservable();
/**
* Set the route and params of the active route
* The function will identify any values in the given URL that start with a
* colon (indicating a URL parameter) and swap it out for the value provided
* in the params argument. It then uses Angular Routers default serialiser to
* build a UrlTree. Params are also converted to Angulars ParamMap.
*/
set(route: string, params: Params = {}) {
const parts = route.split('/');
const url = [];
// For each part of the URL, if it starts with a colon,
// replace it with the corresponding entry in the params object.
for (let index = 0; index < parts.length; index++) {
let part = parts[index];
if (part.startsWith(':')) {
part = params[part.substring(1)];
}
url.push(part);
}
const urlSerializer = new DefaultUrlSerializer();
const tree = urlSerializer.parse(url.join('/'));
const group: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
const segments: UrlSegment[] = group.segments;
this.urlSubject.next(segments);
this.paramMapSubject.next(convertToParamMap(params));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment