无法使用RouterTestingModule测试路由

时间:2018-12-17 21:15:59

标签: angular angular6 angular-routing angular-testing

我有一个使用Routes的组件。我想对路线进行单元测试,但是使用RouterTestingModule可以做到。

我写的spec

import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
....


fdescribe('HomepageContentComponentComponent', () => {
  let component: HomepageContentComponentComponent;
  let fixture: ComponentFixture<HomepageContentComponentComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports:[
        RouterTestingModule.withRoutes([
          {
            path: 'new-practice-question',
            component: NewPracticeQuestionComponent
          }]),
        ReactiveFormsModule,
        HttpClientTestingModule
      ],
      declarations: [ ...
      ],
      providers:[
        {provide: Location, useClass: SpyLocation},
        {provide: LocationStrategy, useClass: MockLocationStrategy},
        {provide: NgModuleFactoryLoader, useClass: SpyNgModuleFactoryLoader}
      ]
    })
    .compileComponents();
    fixture = TestBed.createComponent(HomepageContentComponentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
      it('should navigate to New Questions Component when New Question button is clicked',fakeAsync(()=>{
    let router:Router = TestBed.get(Router);
    let location:Location = TestBed.get(Location);
    console.log('initial router is ',router);
    console.log('initial location is ',location);
    //router.initialNavigation();
    router.navigate(['new-practice-question']).then(()=>{
      console.log('new router is ',router);
      console.log('new location is ',location);
      expect(location.path()).toBe('/new-practice-question');
    });


  }));
});

我面临两个问题 1)path()似乎没有在Location中定义,但是我在网上看到的大多数示例都使用path()。因此expect中的比较失败。 2)我必须为providers等显式提供SpyLocation。为什么?我在网上看到的大多数示例似乎只使用RouterTestingModule.withRoots,而无需显式提供providers。如果我不这样做,则会出现错误no providers for Location!

1 个答案:

答案 0 :(得分:0)

使其正常工作。 .gitignore的定义有误,原因不明。当我添加Location

时,该测试有效