我有一个使用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!
答案 0 :(得分:0)
使其正常工作。 .gitignore
的定义有误,原因不明。当我添加Location