title: Mocking Observable with Jest - rxjs
body: <p>I have a simple Observable piping from another Observable that I want to test.</p>
  
  <pre><code>const loginState$ = messageBusObservables.loginState$.pipe(
      startWith({ isLoggedIn: false })
      pluck('isLoggedIn'),
      distinctUntilChanged()
    )
  </code></pre>
  
  <p>messageBusObservables is an object of observables. Where loginState$ is an Observable.</p>
  
  <p>In my tests, I thought I would easily be able to mock the './messageBus' module like this: (how the module is imported is irrelevant, but import preferred)</p>
  
  <pre><code>import { of } from 'rxjs'
  import './messageBus'
  jest.mock('./messageBus', () =&gt; ({
    loginState$: of({ isLoggedIn: true }),
  }))
  </code></pre>
  
  <p>However, Jest throws the error:</p>
  
  <blockquote>
    <p>babel-plugin-jest-hoist: The module factory of <code>jest.mock()</code> is not allowed to reference any out-of-scope variables.
        Invalid variable access: of</p>
  </blockquote>
  
  <p>I have tried, putting it in a <code>jest.fn()</code> I have tried extracting <code>of({ isLoggedIn: true })</code> to a variable. But I keep getting the same error from jest.</p>
  
  <p>So how can I mock the input into my Observables using Jest? I'll run into the same problem with other observables using .merge, .zip etc.</p>
  
  <p>It needs to be a real observable that is the input of my other observables. I just want to mock the value with something like <code>of()</code> rather than mocking an object, with a method on it, that returns an object with a .pipe method etc. (I don't want to mock the functionality of an Observable). I want to pass it a real observable with a value set in my unit test.</p>
  
  <p>I also need these mocks to be dynamic. So the mock from 1 assertion can be different from the mock in the next assertion. (clearing them with something like a beforeEach)</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I also tried to use babel-plugin-rewire to mock this module, this worked fine in the *.test.js file where I was mocking it. But in the actual file no matter what I set the export to using rewire, it always got imported as the original Observable.</p>