【发布时间】:2017-06-28 10:51:14
【问题描述】:
我有带有 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();
});
});
我正在根据答案 here 传递 ActivatedRoute 值,但我收到错误消息。所以我的问题是 - 我应该传递什么作为 ActivatedRoute 才能订阅和取消订阅? Example Plunker.
【问题讨论】:
-
最好在取消订阅周围加上条件
if (this.subscription)。我刚刚尝试了测试代码,并在测试中的 ngOnDestroy 函数调用上放置了 500 毫秒的setTimeout,然后测试通过了。我想实际初始化订阅需要一些时间。 -
@JacobNotte 这对我有用!只是为了确保
this.subscription不是undefined!
标签: javascript unit-testing angular karma-jasmine angular-routing