0
votes

I am trying to run karma tests on an Angular component called UserComponent. In this component, I have a my ngOnInit doing this:

  ngOnInit() {
    const stream = this.tokenSvc.authTokens.pipe(switchMap((x) => {
      this.infoSvc.fetchUserInfo().toPromise().then((y) => {
        localStorage.setItem("oauth", this.tokenSvc.oAuthToken);
        localStorage.setItem("username", y["id"]);
        this.infoSvc.updateAlbums()
        this.infoSvc.login(y["id"], this.tokenSvc.oAuthToken).toPromise().then((z) => {
          this.router.navigate(['home']);
        })
      }).catch((e) => {
        console.log("unable to fetch user data")
      });
      return this.infoSvc.fetchUserInfo();
    }));

    this.stream = stream.subscribe((x) => 
      this.user = x
    )
  }

The key to the error is the this.router.navigate(['home']); line. For some reason it can't match home to a component from my routing. Though, the component is in my routing:

  {
    path:'home',
    component: HomeComponent,
    canActivate: [
      AuthGuard
    ]
  }

In my testing, I read this stackoverflow post that said to try adding the withRoutes to the test, though this didn't work. Here is my testing code

describe('UserComponent', () => {
  let component: UserComponent;
  let fixture: ComponentFixture<UserComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FaIconComponent, AlbumInfoComponent, UserComponent, HomeComponent, SearchBarComponent, RecentReleaseComponent, YourQueueComponent ],
      imports: [FormsModule , HttpClientTestingModule, RouterTestingModule.withRoutes([{path: 'home', component: HomeComponent}])],
      providers: [AuthService, TokenService, InfoService]
    })
    .compileComponents();
  }));

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

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

There, you can see me try the withRoutes and add path and component overrides to no luck. Here is the full error:

Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
Error: Cannot match any routes. URL Segment: 'home' 
1

1 Answers

2
votes

You need to initialize the router into your test suite :

// add a router declaration at the top of your describe
let router: Router;

// enhance your second beforeEach by instancing the router and initializing the navigation
beforeEach(() => {
  fixture = TestBed.createComponent(UserComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();

  router = TestBed.get(Router);
  router.initialNavigation();
})