我有带有 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 方法时(或当我运行多个测试时),我得到“无法读取未定义的属性‘取消订阅’”。
我的规范文件:
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 值 here ,但我收到错误。所以我的问题是 - 我应该通过什么作为 ActivatedRoute 才能订阅和取消订阅? Example Plunker .
最佳答案
模拟您的服务时只需使用观察者:
{
provide: ActivatedRoute,
useValue: { data: Observable.of({ name: 'Stepan' }) }
}
关于javascript - Angular 2 单元测试 "Cannot read property ' 取消订阅未定义的“,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42153464/