title: React / Jest: how to test store.dispatch is called
body: <p>I am new in Redux and Jest and I am struggling on a problem. I want to write the test for this file:</p>
  
  <p><code>eventListeners.js</code></p>
  
  <pre><code>import store from '@/store';
  
  chrome.runtime.onMessage.addListener((request) =&gt; {
    if (request.type === 'OAUTH_SESSION_RESTORED') {
      store.dispatch(completeLogin());
    }
  });
  </code></pre>
  
  <p>I have this file:</p>
  
  <p><code>eventListeners.test.js</code></p>
  
  <pre><code> it('dispatches completeLogin when OAUTH_SESSION_RESTORED received', () =&gt; {
      // I have made a mock of `chrome.runtime.sendMessage` so the listener defined in eventListeners.js is called when doing that
      chrome.runtime.sendMessage({ type: 'OAUTH_SESSION_RESTORED' });
  
      // I want to test that store.dispatch got called
    });
  </code></pre>
  
  <p>However I don't succeed to test that the <code>dispatch</code> method of the store is called.</p>
  
  <p><strong>What I have tried so far:</strong></p>
  
  <p>1) trying to mock directly the method dispatch of the store (eg. doing <code>jest.spyOn(store, 'dispatch')</code> , <code>jest.mock('@/store')</code>). </p>
  
  <p>However nothing seems to work. I think it is because the store used in <code>eventListeners.js</code> is not the one in the specs. So, mocking it does not do anything</p>
  
  <p>2) Using the <code>redux-mock-store</code> library, as described in <a href="https://redux.js.org/recipes/writing-tests" rel="nofollow noreferrer">https://redux.js.org/recipes/writing-tests</a> . </p>
  
  <p>Doing</p>
  
  <pre><code>const store = mockStore({})
  chrome.runtime.sendMessage({ type: 'OAUTH_SESSION_RESTORED' });
  expect(store.getActions()).toEqual([{ type: 'LOGIN_COMPLETE' }])
  </code></pre>
  
  <p>However, same issue (I guess): the store used in the spec is not the same as in the <code>eventListeners.js</code> . <code>store.getActions()</code> returns <code>[]</code>.</p>
  
  <p>Is there a good way to test that <code>store.dispatch</code> get called?</p>
  
  <p>===================================</p>
  
  <p>For now, what I do is that I subscribe to the store and I try to see if the store has change. As described in <a href="https://github.com/reduxjs/redux/issues/546" rel="nofollow noreferrer">https://github.com/reduxjs/redux/issues/546</a> </p>
  
  <pre><code>it('dispatches completeLogin when OAUTH_SESSION_RESTORED received', () =&gt; {
      const storeChangedCallback = jest.fn()
      store.subscribe(storeChangedCallback)
      chrome.runtime.sendMessage({ type: 'OAUTH_SESSION_RESTORED' });
      expect(storeChangedCallback).toHaveBeenCalled();
      })
  </code></pre>
  
  <p>Is there a better way? Did I missed something?</p>
  
  <p>Thank you for your answers.</p>