如何使用Angular路径参数正确执行单元测试?

时间:2018-06-27 08:28:46

标签: angular unit-testing

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap, Params } from '@angular/router';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Component({
  // selector: 'app-view1',
  template: '<h1>{{ title$ | async }}</h1>',
  // templateUrl: './view1.component.html',
  // styleUrls: ['./view1.component.css']
})
export class View1Component implements OnInit {
  public title$: Observable<string>;

  constructor(private _route: ActivatedRoute) {
  }

  ngOnInit() {
    console.log('view1 init');
    this.title$ = this._route.params.pipe(
      map((value: Params) => {
        console.log(value);
        return value['title'] || 'no title';
      })
    );
  }
}

我有一个如上所述的简单视图组件。该组件将使用<router-outlet>.加载到我的may组件中。模块文件中的 Routes 配置如下所示。

export const appRoutes: Routes = [
  { path: 'view1', component: View1Component },
  { path: 'view1/:title', component: View1Component }
];

我正在努力为此组件实施单元测试。更具体地说,我不知道如何将ActivatedRoute值正确地注入组件,以及如何处理异步情况。

1 个答案:

答案 0 :(得分:0)

您可以在测试规范文件中使用模拟ActivatedRoute,因为这是组件测试,因此在加载组件之前不会获得activated route详细信息。

您可以通过以下方式启动测试组件:

let activatedRoute = jasmine.createSpyObj<ActivatedRoute>("ActivatedRoute", ['params']); // create mock object   
activatedRoute.params = Observable.of({id:'123'});   // set mock params or any other stuff

beforeEach(() => {    
    //Configuring testing environment
    TestBed.configureTestingModule({
        imports: [RouterTestingModule],
        providers: [MyProvider,
              // override ActivateRoute injector with mock object
            {provide: ActivatedRoute, useValue: activatedRoute}
        ],

    });
});

有许多教程介绍了如何在angular中测试异步方法。

https://codecraft.tv/courses/angular/unit-testing/asynchronous/

https://angular.io/guide/testing#async-test-with-fakeasync

相关问题