Angular 使用Karma/Jasmine进行单元测试:

Angular 使用Karma/Jasmine进行单元测试:,angular,typescript,unit-testing,jasmine,karma-jasmine,Angular,Typescript,Unit Testing,Jasmine,Karma Jasmine,我已经在我的组件中插入了if-else条件,以便在登录后将我转发到特定的URL。但是,我的单元测试现在失败,出现以下错误: 1) 应该创造 另一种成分 Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'testroute' 如果没有if-else条件,一切正常,因此我确信这就是我问题的原因。有趣的是,我没有测试任何与ngOnInit()生命周期中的代码相关的东西。更有趣的是

我已经在我的组件中插入了if-else条件,以便在登录后将我转发到特定的URL。但是,我的单元测试现在失败,出现以下错误:

1) 应该创造

另一种成分

 Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'testroute'
如果没有if-else条件,一切正常,因此我确信这就是我问题的原因。有趣的是,我没有测试任何与ngOnInit()生命周期中的代码相关的东西。更有趣的是,不是MyComponent的测试失败了,而是另一个组件的测试失败了

我的组件(MyComponent)如下所示:

export class MyComponent implements OnInit {

  routes = Constants.routes;

  constructor(private router: Router,
    private myService: MyService) {
  }

  ngOnInit() {
    if (this.myService.context === 'TEST') {
      this.router.navigate([routes.testroute + this.myService.context]);
    } else {
      this.router.navigate([routes.testroute]);
    }
  }
}
<router-outlet></router-outlet>
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([]),
      ],
      providers: [
        PathLocationStrategy
      ],
      declarations: [AnotherComponent],
    }).compileComponents();
  }));

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
模板如下所示:

export class MyComponent implements OnInit {

  routes = Constants.routes;

  constructor(private router: Router,
    private myService: MyService) {
  }

  ngOnInit() {
    if (this.myService.context === 'TEST') {
      this.router.navigate([routes.testroute + this.myService.context]);
    } else {
      this.router.navigate([routes.testroute]);
    }
  }
}
<router-outlet></router-outlet>
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([]),
      ],
      providers: [
        PathLocationStrategy
      ],
      declarations: [AnotherComponent],
    }).compileComponents();
  }));

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

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

导入路由器测试模块时,需要配置路由。我通常使用虚拟组件设置路由

TestBed.configureTestingModule({
  imports: [
    CommonModule,
    RouterTestingModule.withRoutes([
      // add routes here
      { path: 'testroute', component: DummyComponent }
    ]),
 ],
 providers: [
    PathLocationStrategy
  ],
 declarations: [AnotherComponent],
}).compileComponents();