Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度2单元测试“;无法读取属性';取消订阅';“未定义”的定义;_Javascript_Unit Testing_Angular_Karma Jasmine_Angular Routing - Fatal编程技术网

Javascript 角度2单元测试“;无法读取属性';取消订阅';“未定义”的定义;

Javascript 角度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

我有一个带有ngOnInit和Ngondestory方法以及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();
    }
}
当我从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
,现在工作正常。