Angular 2单元测试"无法读取属性'取消订阅'未定义"

时间:2017-02-10 07:08:56

标签: javascript unit-testing angular karma-jasmine angular-routing

我有使用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方法时(或者当我运行多个测试时)。

我的spec文件:

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

2 个答案:

答案 0 :(得分:2)

在模拟服务时使用观察者:

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

答案 1 :(得分:1)

您应首先导入订阅。

import { Subscription } from 'rxjs/Subscription';