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

Unit testing Angular with Karma/Jasmine:

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

1) should create

AnotherComponent

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

没有 if else 条件一切正常,所以我确定这就是我的问题的原因。有趣的是,我没有测试与 ngOnInit() 生命周期内的代码相关的任何内容。更有趣的是,不是 MyComponent 的测试失败了,而是另一个 Component 的测试失败了。

我的组件 (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();
  });

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

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