簡體   English   中英

Angular 測試:未捕獲錯誤:未捕獲(承諾中):錯誤:無法匹配任何路由。 URL 段:“家”

[英]Angular Testing: Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'

我正在嘗試在名為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
    ]
  }

在我的測試中,我閱讀了這篇 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' 

您需要將路由器初始化到您的測試套件中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM