【问题标题】:Angular 2 unit testing "Cannot read property 'unsubscribe' of undefined"Angular 2 单元测试“无法读取未定义的属性‘取消订阅’”
【发布时间】: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


【解决方案1】:

您应该先导入订阅。

import { Subscription } from 'rxjs/Subscription';

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 谢谢你的回答,我试过params: Observable.of({name: 'Stepan'})而不是data: Observable.of({ name: 'Stepan' }),现在可以正常工作了。
    猜你喜欢
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2018-11-11
    • 1970-01-01
    • 2017-04-04
    相关资源
    最近更新 更多