【问题标题】:Unit testing Angular with Karma/Jasmine:使用 Karma/Jasmine 对 Angular 进行单元测试:
【发布时间】:2020-02-20 12:11:00
【问题描述】:

我在我的组件中插入了一个 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();
  });

【问题讨论】:

    标签: angular typescript unit-testing jasmine karma-jasmine


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多