Angular 2: Testing components with router

后端 未结 2 1491
一整个雨季
一整个雨季 2021-01-18 06:29

I am writing the simplest component that is using a routeLink:

@Component({
    selector: \'memorySnippet\',
    templateUrl: \'
相关标签:
2条回答
  • 2021-01-18 07:00

    You should have a beforeEachProviders method looking like:

    import {MockApplicationRef} from '@angular/core/testing';
    
    beforeEachProviders(() => [
      ROUTER_PROVIDERS,
      provide(APP_BASE_HREF, {useValue: '/'}),
      provide(ROUTER_PRIMARY_COMPONENT, {useValue: YourComponent}),
      provide(ApplicationRef, {useClass: MockApplicationRef}
    ]);
    

    MockApplicationRef is provided by the framework for this kind of tests.

    0 讨论(0)
  • 2021-01-18 07:08

    For RC4 with new router now use ...

    beforeEach(() => addProviders([
      APP_ROUTER_PROVIDERS, // must be first
      {provide: APP_BASE_HREF, useValue: '/'}, // must be second
      {provide: ActivatedRoute, useClass: Mock},
      {provide: Router, useClass: Mock}
    ]));
    

    A github project using this approach is ...

    https://github.com/danday74/angular2-coverage

    0 讨论(0)
提交回复
热议问题