unable to test Routing using RouterTestingModule

亡梦爱人 提交于 2019-12-24 00:36:11

问题


I have a component which uses Routes. I want to unit test the routes but am unale to do so using RouterTestingModule.

The spec I have written is

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');
    });


  }));
});

I am facing two issues 1) path() doesn't seem to be defined in Location but most of the examples I have seen online use path(). So the comparison in expect is failing. 2) I had to explicitly provide providers for SpyLocation etc. Why? Most of the example I have seen online seem to just use RouterTestingModule.withRoots without need to explicitly provide providers. If I don't do so, I get error no providers for Location!


回答1:


Got it working. The wrong definition of Location was being picked for unknown reason. The test worked when I added import {Location} from "@angular/common";



来源:https://stackoverflow.com/questions/53823091/unable-to-test-routing-using-routertestingmodule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!