title: Angular 2 Testing: Spying on ngOnInit() in beforeEach?
body: <h1>Context</h1>
  <p>My issue is that my ngOnInit function calls many sub functions asynchronously by using Firestore to populate a form from one document as well as subscribing to various collections to display lists of data. This gets very tedious to test as I then have to ensure things are subscribing properly and values are being returned in the correct order.</p>
  <p>According to the <a href="https://angular.io/guide/testing#!#isolated-unit-tests" rel="nofollow noreferrer">Angular docs</a>:</p>
  <blockquote>
  <p>However, it's often more productive to explore the inner logic of application classes with isolated unit tests that don't depend upon Angular. Such tests are often smaller and easier to read, write, and maintain.</p>
  </blockquote>
  <p>Which in my opinion would make preventing the ngOnInit (through a spy) a valid way of</p>
  <ol>
  <li><p>Isolating tests and</p>
  </li>
  <li><p>Reducing complexity when initializing the tests</p>
  </li>
  </ol>
  <p>You can then explicitly call each function separately and only test what is needed, instead of having ngOnInit calling the functions (and possible you as well).</p>
  <p>This is exactly how I have gone about it so far:</p>
  <h3>Component</h3>
  <pre><code>ngOnInit() {
      console.log('init');
      this.setup();
  }
  
  setup() {
      this.firebaseService.setup(_ =&gt; {
          this.checkNewOrEdit();
      });
  }
  </code></pre>
  <p>...</p>
  <h2>Spec</h2>
  <p>...</p>
  <pre><code>beforeEach(() =&gt; {
      fixture = TestBed.createComponent(Component);
      component = fixture.componentInstance;
      spyOn(component, 'ngOnInit');
      fixture.detectChanges();
  });
      
  it('should be created', () =&gt; {
      fixture.whenStable().then(_ =&gt; {
          expect(component).toBeTruthy();
      });
  });
      
     
  it('should call checkNewOrEdit() on setup()',
      () =&gt; {
          spyOn(component, 'checkNewOrEdit');
          callbackValue = 'success';
          component.setup();
          expect(component.checkNewOrEdit).toHaveBeenCalled();
      }
  );
  </code></pre>
  <p>Which is working fine for me so far.</p>
  <p><strong>Is this an acceptable solution?</strong> Or are there better ways of going about this?</p>