Home > Back-end >  pipe is undefined - ActivatedRoute
pipe is undefined - ActivatedRoute

Time:01-22

I have the following component

export class MyComponent implements OnInit {
  exportItems: boolean;
  constructor(
    private service: Service,
    private route: ActivatedRoute
  ) {}

  ngOnInit(): void {
    this.route.url.pipe(take(1)).subscribe(() => {
      const childData = this.route.snapshot.firstChild.data;
      this.exportItems= childData.exportItems;
    });
  }

  closeClicked(): void {
    window.close();
  }

  exportClicked(): void {
    this.service.exportItems.next(true);
  }
}

My test looks like the following

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let router: Router;
  let aRoute: ActivatedRoute;
  const route = { data: of({ label: 'hello' }) } as any as ActivatedRoute;

  const moduleDef: TestModuleMetadata = {
    declarations: [MyComponent],
    providers: [
      {
        provide: ActivatedRoute,
        useValue: { url: 'path/to/something', data: route }
      }
    ]
  };
  setUpTestBed(moduleDef);

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    router = TestBed.inject(Router);
    aRoute = TestBed.inject(ActivatedRoute);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('close window when button clicked', () => {
    spyOn(window, 'close');
    component.closeClicked();
    expect(window.close).toHaveBeenCalled();
  });
});

I am running into the following error

Chrome Headless 92.0.4515.107 (Windows 10) MyComponent should close window when button clicked FAILED TypeError: this.route.url.pipe is not a function at MyComponent.ngOnInit (src/app/src/test/my.component.ts:19:20) at callHook (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:2526:1)

I have read / tried items from multiple posts online and have tried to debug it but have not reached a solution yet.

Thank you for your time and help.

CodePudding user response:

The issue is the following:

In your component logic, you pipe the url property of the route object:

this.route.url.pipe(take(1))

but in your test, you mock it with a static string, instead of with an observable:

{
 provide: ActivatedRoute,
 useValue: { url: 'path/to/something', data: route }
}

This is why you get that error. In order for the test to work, you should mock the url value with an observable, e.g:

{
 provide: ActivatedRoute,
 useValue: { url: of('path/to/something'), data: route }
}
  •  Tags:  
  • Related