Search code examples
angulartypescriptunit-testingroutes

"TypeError: Cannot read property 'pipe' of undefined" - Do I miss additional setup in my unit tests ( Angular / Unit testing / ActivatedRoute )


I'm currently facing an issue where I have an Observable based on the paramMap of my activatedRoute

this.current$ = this.route.paramMap.pipe(map(paramMap => paramMap.get('title')));

It's working nice on my front-end, but I recently started using angular unit tests, and I have a very basic test to start out. Which currently only holds:


  beforeEach(() => {
    fixture = TestBed.createComponent(BannerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeDefined();
  });

  it('should create', () => {
    expect(component).toBeDefined();
  });

For some reason, when running my test. It is erroring on the following.

TypeError: Cannot read property 'pipe' of undefined

I have some other simple tests setup, but they all fail on this above message. Do I miss something here?


Solution

  • You can try to mock the Route like:

     `` 
        {
          provide: ActivatedRoute,
          useValue: {
            snapshot: {
              paramMap: {
                get: (key: string) => {
                  switch (key) {
                    case 'title':
                      return 'my title';
                    case 'subtitle':
                      return 'my subtitle'
                  }
                }
              },
            },
          },
        }``