Angular 2 个单元测试 "Cannot read property 'unsubscribe' of undefined"

Angular 2 unit testing "Cannot read property 'unsubscribe' of undefined"

我有带有 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();
    }
}

当我从 spec 文件调用 ngOnDestroy 方法时(或者当我 运行 多次测试时)我得到 "Cannot read property 'unsubscribe' of undefined"。

我的规范文件:

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 才能订阅和取消订阅? Example Plunker.

您应该先导入订阅。

import { Subscription } from 'rxjs/Subscription';

模拟您的服务时只需使用观察者:

{
    provide: ActivatedRoute,
    useValue: { data: Observable.of({ name: 'Stepan' }) }
}