无法使用 RouterTestingModule 测试路由 [英] unable to test Routing using RouterTestingModule

查看:20
本文介绍了无法使用 RouterTestingModule 测试路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Routes 的组件.我想对路由进行单元测试,但我无法使用 RouterTestingModule 这样做.

I have a component which uses Routes. I want to unit test the routes but am unale to do so using 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) 我必须为 SpyLocation 等明确提供 providers.为什么?我在网上看到的大多数示例似乎只是使用 RouterTestingModule.withRoots 而无需明确提供 providers.如果我不这样做,我会收到错误 no providers for Location!

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!

推荐答案

成功了.由于未知原因选择了错误的 Location 定义.当我添加 import {Location} from "@angular/common";

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";

这篇关于无法使用 RouterTestingModule 测试路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆