在为路由路径创建测试套件时遇到了同样的问题:
{
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');
});
希望这可以帮助!