angularunit-testingangular-activatedroute

Mock Activated Route With Params in Angular


Question

How to mock ActivatedRoutes in my unit tests?

Service:

  constructor(
    private route: ActivatedRoute,
    private knowledgeModelService: KnowledgeModelService
  ) {
    route.params.pipe(map(p => p.modelId)).subscribe((modelId) => {
      this.modelId = modelId;
    });
  }

My unit test:

With mock class

  class ActivatedRouteMock {
    // params = of([{modelId: 'test1'}]);
    params = { paramMap: of( convertToParamMap( { modelId: 'test1' } ) ) }
  }

...

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ StatsComponent ],
      providers: [
        {
          provide: ActivatedRoute, useClass: ActivatedRouteMock
        },

I tried diff. approaches from:

Angular2 RC5 Mock Activated Route Params

Angular2 how to Mock Activated Route Params subscribed

Unit test angular activate route correctly

Angular 4 - Failed: Can't resolve all parameters for ActivatedRoute: (?, ?, ?, ?, ?, ?, ?, ?)

But I'm not getting anywhere.

Err:

route.params.pipe is not a function

Solution

  • Have you tried it like that?

    class ActivatedRouteMock {
        params = of( { modelId: 'test1' } )
    }