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

I have sample TestComp with ngOnInit and ngOnDestroy methods and ActivatedRoute subscription.@Component

I have sample TestComp with ngOnInit and ngOnDestroy methods and ActivatedRoute subscription.

@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();
    }
}

I am getting "Cannot read property 'unsubscribe' of undefined" when I call ngOnDestroy method from spec file (or when I am running multiple tests).

My spec file:

describe('TestComp', () => {
    let p: 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'})
        //   }
        // }
      ]
    })
    pileComponents()
    .then(() => {
          fixture = TestBed.createComponent(TestComp);        
          fixture.detectChanges();
    })
    }));

  it('TestComp successfully initialized', () => {
    fixtureponentInstance.ngOnInit();
    expect(fixtureponentInstance).toBeDefined()
    fixtureponentInstance.ngOnDestroy();
  });
});

I am passing ActivatedRoute value based on answers here, but I am getting error. So my question is - what should I pass as ActivatedRoute to make it possible to subscribe and unsubscribe? Example Plunker.

I have sample TestComp with ngOnInit and ngOnDestroy methods and ActivatedRoute subscription.

@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();
    }
}

I am getting "Cannot read property 'unsubscribe' of undefined" when I call ngOnDestroy method from spec file (or when I am running multiple tests).

My spec file:

describe('TestComp', () => {
    let p: 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'})
        //   }
        // }
      ]
    })
    .pileComponents()
    .then(() => {
          fixture = TestBed.createComponent(TestComp);        
          fixture.detectChanges();
    })
    }));

  it('TestComp successfully initialized', () => {
    fixture.ponentInstance.ngOnInit();
    expect(fixture.ponentInstance).toBeDefined()
    fixture.ponentInstance.ngOnDestroy();
  });
});

I am passing ActivatedRoute value based on answers here, but I am getting error. So my question is - what should I pass as ActivatedRoute to make it possible to subscribe and unsubscribe? Example Plunker.

Share Improve this question edited May 23, 2017 at 12:25 CommunityBot 11 silver badge asked Feb 10, 2017 at 7:08 styopdevstyopdev 2,6644 gold badges37 silver badges55 bronze badges 2
  • 1 it's a good practice to put a conditional if (this.subscription) around the unsubscription. I've just tried the testcode and put a setTimeout of 500ms on the ngOnDestroy function call in your test and then the test passes. I guess it takes some time until the subscription is actually initialised. – Jacob Notte Commented Feb 10, 2017 at 7:38
  • 1 @JacobNotte This worked for me! Had just to ensure that this.subscription was not undefined! – SrAxi Commented Mar 1, 2017 at 13:23
Add a ment  | 

2 Answers 2

Reset to default 2

Just use observer when mock your service:

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

You should import Subscription first.

import { Subscription } from 'rxjs/Subscription';

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745350724a4623814.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信