我有一个非常简单的组件,如下所示。请承担所有相关进口。
//my-component.component.ts
//imports, decorator, etc.
routingNumber: number;
ngOnInit() {
this.route.params.subscribe(
params => {
this.routingNumber = +params['id'];
}
);
}
我还有一个测试文件,如下所示。再一次,请假设所有相关的进口声明。我有一个用模拟的ActivateRoute代替实际的ActivatedRoute,并带有关联的observable。我给人的印象是,调用fix.onChanges()会运行ngOnInit,并将routingNumber属性值设置为可观察对象传递的值,但是在运行测试时,它始终返回undefined。
//my-component.component.spec.ts
//imports, describe, etc.
class mockActivatedRoute {
params = {
subscribe() {
return of({id: '1'});
}
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
NoteService,
{provide: ActivatedRoute, useClass: mockActivatedRoute},
{provide: DataStorageService, useValue: dataServiceStub}
],
declarations: [MyComponent],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('should expect 1 as the route parameter', async(() => {
fixture.detectChanges();
expect(component.routingNumber).toEqual(1);
});
答案 0 :(得分:1)
您可以尝试--
params = of({id: '1'});
params.subscribe( params => { console.log(params)
})