测试角度。 TypeError:this._platformStrategy.getBaseHref不是函数

时间:2018-05-30 07:40:27

标签: angular unit-testing routing jasmine karma-jasmine

我想测试路由。我试过这个剧本:

describe('Router: App', () => {
    let location: Location;
    let router: Router;
    let fixture;
    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [
                AlarmsTableComponent,
                AddAlarmsFormComponent,
                EditAlarmsFormComponent,
                LoginComponent,
                DataFilterPipe
            ],
            imports: [RouterTestingModule, DataTableModule, ReactiveFormsModule, FormsModule, HttpClientTestingModule, HttpModule],
            providers: [Location, LocationStrategy, AlarmsService, DataFilterPipe, AuthService, ConnectionBackend, HttpModule,
                {
                    provide: APP_BASE_HREF, useValue: '/page' }
                ]
        });

        router = TestBed.get(Router);
        location = TestBed.get(Location);

        fixture = TestBed.createComponent(MainComponent);
        router.initialNavigation();
    });
    it('navigate to "" redirects you to /page', fakeAsync(() => {
        router.navigate(['page']);
        tick();
        expect(location.path()).toBe('/page');
    }));
});

当我ng test时,结果就是这个错误:

  

TypeError:this._platformStrategy.getBaseHref不是函数

编辑:

describe('Router: App', () => {
    let location: Location;
    let router: Router;
    let fixture;
    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [
                AlarmsTableComponent,
                AddAlarmsFormComponent,
                EditAlarmsFormComponent,
                LoginComponent,
                DataFilterPipe
            ],
            imports: [RouterTestingModule, DataTableModule, ReactiveFormsModule, FormsModule, HttpClientTestingModule, HttpModule],
 providers: [Location, AuthService, AlarmsService, DataFilterPipe,
            {provide: LocationStrategy, useClass: PathLocationStrategy }],
        });

        router = TestBed.get(Router);
        location = TestBed.get(Location);

        fixture = TestBed.createComponent(MainComponent);
        router.initialNavigation();
    });
    it('navigate to "" redirects you to /page', fakeAsync(() => {
        router.navigate(['page']);
        tick();
        expect(location.path()).toBe('/page');
    }));
});

现在说明:

  

错误:没有设置基本href。请提供APP_BASE_HREF的值   令牌或向文档添加基本元素。

1 个答案:

答案 0 :(得分:3)

首先,删除HttpModule中的providers。他不能在那里,只是在imports

修改您提供LocationStrategy的方式,如下所示:

{ provide: LocationStrategy, useClass: PathLocationStrategy },
{ provide: APP_BASE_HREF, useValue: '/page' }

有关PathLocationStrategy official doc的更多信息,请参阅