Angular Тестирование: Uncaught Ошибка: Uncaught (в обещании): Ошибка: не удается сопоставить ни один маршрут. Сегмент URL: «дом» - PullRequest
0 голосов
/ 03 мая 2020

Я пытаюсь запустить тесты кармы на компоненте Angular с именем UserComponent. В этом компоненте у меня есть мой ngOnInit, который делает это:

  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
    )
  }

Ключом к ошибке является строка this.router.navigate(['home']);. По какой-то причине он не может сопоставить дом с компонентом из моей маршрутизации. Тем не менее, компонент находится в моей маршрутизации:

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

В моем тестировании я прочитал эту публикацию stackoverflow , в которой говорится, что нужно попытаться добавить withRoutes в тест, хотя это не сработало , Вот мой тестовый код

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();
  });
});

Там вы можете увидеть, как я пробую withRoutes и добавляю пути и переопределения компонентов, но безуспешно Вот полная ошибка:

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

1 Ответ

1 голос
/ 04 мая 2020

Вам нужно инициализировать маршрутизатор в ваш набор тестов:

// 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();
})

...