【问题标题】:Angular Testing: Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'角度测试:未捕获错误:未捕获(承诺):错误:无法匹配任何路由。网址段:“家”
【发布时间】:2020-08-18 05:01:00
【问题描述】:

我正在尝试在名为 UserComponent 的 Angular 组件上运行业力测试。在这个组件中,我有一个我的 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']); 行。由于某种原因,它无法将 home 与我的路由中的组件匹配。不过,该组件在我的路由中:

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

在我的测试中,我读到 this stackoverflow post 说尝试将 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' 

【问题讨论】:

    标签: javascript angular testing jasmine karma-runner


    【解决方案1】:

    您需要将路由器初始化到您的测试套件中:

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

    【讨论】:

    • 谢谢!这行得通。我必须为将来的人做一件事:我的其他组件之一也缺少我上面的路由器选项
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2019-02-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    相关资源
    最近更新 更多