我有带有ngOnInit和ngOnDestroy方法以及ActivatedRoute订阅的示例TestComp。
@Component({
selector: 'test',
template: '',
})
export class TestComp implements OnInit, OnDestroy {
constructor (
private route: ActivatedRoute
) {
}
ngOnInit() {
this.subscription = this.route.data
.subscribe(data => {
console.log('data', data.name);
})
;
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
从规范文件调用ngOnDestroy方法时(或在运行多个测试时),出现“无法读取未定义的属性'unsubscribe'”。
我的规格文件:
describe('TestComp', () => {
let comp: TestComp;
let fixture: ComponentFixture<TestComp>;
beforeEach(async(() => {
TestBed
.configureTestingModule({
declarations: [TestComp],
imports: [RouterTestingModule],
providers: [
{
provide: ActivatedRoute,
useValue: {
data: {
subscribe: (fn: (value: Data) => void) => fn({
name: 'Stepan'
})
}
}
}
// { //Also tried this
// provide: ActivatedRoute,
// useValue: {
// params: Observable.of({name: 'Stepan'})
// }
// }
]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(TestComp);
fixture.detectChanges();
})
}));
it('TestComp successfully initialized', () => {
fixture.componentInstance.ngOnInit();
expect(fixture.componentInstance).toBeDefined()
fixture.componentInstance.ngOnDestroy();
});
});
我根据此处的答案传递了ActivatedRoute值,但出现错误。所以我的问题是-我应该通过什么作为ActivatedRoute来进行订阅和退订?示例柱塞。
模拟服务时只需使用观察器即可:
{
provide: ActivatedRoute,
useValue: { data: Observable.of({ name: 'Stepan' }) }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句