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

时间:2020-02-20 12:11:00

标签: 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()生命周期内的代码相关的任何东西。更有趣的是,不是针对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();
  });

1 个答案:

答案 0 :(得分:3)

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

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