Javascript 角度2单元测试“;无法读取属性';取消订阅';“未定义”的定义;
我有一个带有ngOnInit和Ngondestory方法以及ActivatedRoute订阅的示例TestCompJavascript 角度2单元测试“;无法读取属性';取消订阅';“未定义”的定义;,javascript,unit-testing,angular,karma-jasmine,angular-routing,Javascript,Unit Testing,Angular,Karma Jasmine,Angular Routing,我有一个带有ngOnInit和Ngondestory方法以及ActivatedRoute订阅的示例TestComp @Component({ selector: 'test', template: '', }) export class TestComp implements OnInit, OnDestroy { constructor ( private route: ActivatedRoute ) { } ngOnIni
@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();
}
}
当我从spec文件调用ngondstroy方法时(或者当我运行多个测试时),我得到“无法读取未定义的属性‘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();
});
});
description('TestComp',()=>{
let comp:TestComp;
let夹具:组件夹具;
beforeach(异步(()=>{
试验台
.配置测试模块({
声明:[TestComp],
导入:[RouterTestingModule],
供应商:[
{
提供:激活的路由,
使用价值:{
数据:{
订阅:(fn:(值:数据)=>void)=>fn({
姓名:“Stepan”
})
}
}
}
//{//我也试过这个
//提供:激活的路由,
//使用价值:{
//params:Observable.of({name:'Stepan'})
// }
// }
]
})
.compileComponents()
.然后(()=>{
fixture=TestBed.createComponent(TestComp);
fixture.detectChanges();
})
}));
它('TestComp已成功初始化',()=>{
fixture.componentInstance.ngOnInit();
expect(fixture.componentInstance).toBeDefined()
fixture.componentInstance.ngondestory();
});
});
我根据答案传递ActivatedRoute值,但得到的是错误。所以我的问题是-我应该传递什么作为ActivatedRoute以使订阅和取消订阅成为可能?
.您应该先导入订阅
import { Subscription } from 'rxjs/Subscription';
模拟您的服务时只需使用observer即可:
{
provide: ActivatedRoute,
useValue: { data: Observable.of({ name: 'Stepan' }) }
}
在取消订阅前后放置一个有条件的
if(this.subscription)
,这是一个很好的做法。我刚刚尝试了testcode,在测试中对Ngondestory函数调用设置了500ms的setTimeout
,然后测试通过了。我想订阅需要一段时间才能真正初始化。@JacobNotte这对我来说很有效!必须确保此订阅
不是未定义的
!感谢您的回答,我尝试了({name:'Stepan'})的params:Observable.of
而不是({name:'Stepan'})的data:Observable.of
,现在工作正常。