为路由路径创建测试套件时遇到以下相同问题:
{
path: 'edit/:property/:someId',
component: YourComponent,
resolve: {
yourResolvedValue: YourResolver
}
}
在组件中,我将传递的属性初始化为:
ngOnInit(): void {
this.property = this.activatedRoute.snapshot.params.property;
...
}
运行测试时,如果未在模拟的ActivatedRoute“ useValue”中传递属性值,则在使用“ fixture.detectChanges()”检测更改时,您将变得不确定。这是因为ActivatedRoute的模拟值不包含属性params.property。然后,需要模拟useValue具有这些参数,以便灯具在组件中初始化“ this.property”。您可以将其添加为:
let fixture: ComponentFixture<YourComponent>;
let component: YourComponent;
let activatedRoute: ActivatedRoute;
beforeEach(done => {
TestBed.configureTestingModule({
declarations: [YourComponent],
imports: [ YourImportedModules ],
providers: [
YourRequiredServices,
{
provide: ActivatedRoute,
useValue: {
snapshot: {
params: {
property: 'yourProperty',
someId: someId
},
data: {
yourResolvedValue: { data: mockResolvedData() }
}
}
}
}
]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(YourComponent);
component = fixture.debugElement.componentInstance;
activatedRoute = TestBed.get(ActivatedRoute);
fixture.detectChanges();
done();
});
});
您可以开始测试,例如:
it('should ensure property param is yourProperty', async () => {
expect(activatedRoute.snapshot.params.property).toEqual('yourProperty');
....
});
现在,假设您要测试其他属性值,然后可以将模拟的ActivatedRoute更新为:
it('should ensure property param is newProperty', async () => {
activatedRoute.snapshot.params.property = 'newProperty';
fixture = TestBed.createComponent(YourComponent);
component = fixture.debugElement.componentInstance;
activatedRoute = TestBed.get(ActivatedRoute);
fixture.detectChanges();
expect(activatedRoute.snapshot.params.property).toEqual('newProperty');
});
希望这可以帮助!