javascript - Angular Testing : Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL 段: 'home'

标签 javascript angular testing jasmine karma-runner

我正在尝试在名为 UserComponent 的 Angular 组件上运行 karma 测试。在此组件中,我有一个 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' 

最佳答案

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

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

关于javascript - Angular Testing : Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL 段: 'home',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61580873/

相关文章:

javascript - 页面加载时对 Javascript/Jquery 中的 bootstrap modal-body 元素进行排序

javascript - 如何在javascript匿名函数中调用类slibing函数

Javascript(动态)插入数组,然后将所有元素移动到+1下面

函数内的 Angular 访问变量

ruby-on-rails - Factory Girl 多态 has_many, belongs_to

javascript - Testcafe 更容易检查页面上是否存在类选择器

javascript - 获取 DOM 元素流入位置

javascript - 根据下拉列表中的选定值显示表单字段 Angular TypeScript

javascript - 如何在集合中获取数据firebase集合

java - Spring 测试 - @ContextConfiguration 排除基类上下文