Angular testing router params breaks test bed

I figured out the problem/solution.

We're seeing Cannot read property '_lastPathIndex' of undefined because at one point the Angular router expects a _lastPathIndex property on a snapshot object.

The relevant part of the Angular source code looks like this:

if (route.snapshot._lastPathIndex === -1) {
  return new Position(route.snapshot._urlSegment, true, 0);
}

If snapshot is undefined, it will of course raise the error we're seeing.

The problem can be solved by making snapshot not-undefined.

Here's how I did it. My code is a little different from the OP's.

I have a class called MockActivatedRoute that looks like this.

export class MockActivatedRoute {
  parent: any;
  params: any;

  constructor(options) {
    this.parent = options.parent;
    this.params = options.params;
  }
}

Here's how I use it in my test.

let mockActivatedRoute = new MockActivatedRoute({
  parent: new MockActivatedRoute({
    params: Observable.of({ id: '1' })
  })
});

To make the error go away I just added a snapshot property to MockActivatedRoute.

export class MockActivatedRoute {
  parent: any;
  params: any;
  snapshot = {};

  constructor(options) {
    this.parent = options.parent;
    this.params = options.params;
  }
}

You can add snapshot property inside your providers array.

providers: [{ provide: ActivatedRoute, useValue: { snapshot: {} } }]