0

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
Andi Giga
  • 3,744
  • 9
  • 38
  • 68

1 Answers1

2

Have you tried it like that?

class ActivatedRouteMock {
    params = of( { modelId: 'test1' } )
}
bastian
  • 106
  • 2
  • Sorry, I tried it but had a 2nd Observable in it which was wrong mocked so I thought it was still the first. My bad. – Andi Giga Mar 03 '20 at 12:08