1

I am trying to test the ngOnDestroy() method of this component but not able to find the correct way to do that. What should be the right way to do it?

import {Component, OnDestroy} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';


@Component({.......})
export class MyComponent implements OnDestroy {

  private readonly destroyed = new Subject();

  constructor(private readonly route: ActivatedRoute) {
    this.route.queryParams.pipe(takeUntil(this.destroyed)).subscribe(params => {
      // custom code here
    });
  }

  ngOnDestroy() {
    this.destroyed.next();
    this.destroyed.complete();
  }
}
Rudra
  • 1,678
  • 16
  • 29
  • 1
    If you can mock `queryParams` and have it emit values, you can check that the code inside `// custom code here` does not execute after `ngOnDestroy()` has occurred. 1) mock query params 2) spy on `// custom code here` 3) destroy component 4) check `// custom code here` does not execute again. – Alexander Staroselsky May 20 '20 at 17:26
  • 1
    you can refer this [stackoverflow answer](https://stackoverflow.com/a/55530968/7051329). – Kishor Kunal May 20 '20 at 17:47
  • I call it explicitly by doing `component.ngOnDestroy()`. Not sure if it is the best way but it works for me. – AliF50 May 20 '20 at 18:39

0 Answers0