我是角度4的新手,并尝试从单元测试中测试角度4特征router.paramMap之一,以常规方式读取路径参数并在我的应用程序中按预期工作。
{
provide: ActivatedRoute,
useValue: { params: Observable.of({id: 1}) }
}
但是在运行单元测试的时候,即使我通过传递路径参数,我也会收到错误,即不能调用未定义的订阅方法。
iteritems()
请建议
答案 0 :(得分:18)
您需要提供paramMap
而不是params
。 paramMap
的{{1}}类型应为ParamMap
,因此可以使用@angular/router
中的ParamMap
方法将普通对象转换为convertToParamMap()
。
您可以提供如下的模拟ActivatedRoute:
@angular/routing
答案 1 :(得分:6)
我正在使用一种稍微不同的方法来获取组件中的参数:
this.id = this.route.snapshot.paramMap.get('id');
这就是茉莉花测试中对我有用的东西
{
provide: ActivatedRoute,
useValue: {
snapshot: {
paramMap: convertToParamMap({id: 1})
}
}
}
答案 2 :(得分:0)
我们目前正在使用此功能:
{ provide: ActivatedRoute, useValue: { 'params': Observable.from([{ 'id': '1'}]) } },
答案 3 :(得分:0)
您的代码存在问题,为了从网址获取参数,您必须以不同的方式编写代码。
constructor(private router:Router, private actRoute:ActivatedRoute) {
}
ngOnInit() {
this.router.paramMap
.switchMap((params: ParamMap) => {
params.get(id);
....
})
.subscribe((....) => {
....
})
}
答案 4 :(得分:0)
对于需要测试某个组件何时具有某个路由参数以及何时不具有某个路由参数(如/product
和/product/:id
)的任何人,以下对我有用: / p>
组件:
export class PageProductComponent implements OnInit {
id: string | null = null;
constructor(private readonly activatedRoute: ActivatedRoute) { }
ngOnInit(): void {
this.id = this.activatedRoute.snapshot.paramMap.get('id');
}
}
测试:
describe('PageProductComponent ', () => {
let component: PageProductComponent ;
let fixture: ComponentFixture<PageProductComponent >;
let debugEl: DebugElement;
const makeCompiledTestBed = (provider?: object): void => {
const moduleDef: TestModuleMetadata = {
imports: [
RouterTestingModule,
],
declarations: [ PageProductComponent ],
providers: [ ]
};
if (moduleDef.providers && provider) {
moduleDef.providers.push(provider);
}
TestBed.configureTestingModule(moduleDef).compileComponents();
};
const setupTestVars = (): void => {
fixture = TestBed.createComponent(PageProductComponent );
component = fixture.componentInstance;
debugEl = fixture.debugElement;
fixture.detectChanges();
};
describe('When an ID is NOT provided in the URL param', () => {
beforeEach(async(makeCompiledTestBed));
beforeEach(setupTestVars);
it('should list all products', () => {
//...
});
});
describe('When an ID is provided in the URL param', () => {
beforeEach(async(() => {
makeCompiledTestBed({
provide: ActivatedRoute,
useValue: {
snapshot: {
paramMap: convertToParamMap({id: 1234})
}
}
});
}));
beforeEach(setupTestVars);
it('should show a specific product', () => {
//...
});
});
});