3

I am new in Redux and Jest and I am struggling on a problem. I want to write the test for this file:

eventListeners.js

import store from '@/store';

chrome.runtime.onMessage.addListener((request) => {
  if (request.type === 'OAUTH_SESSION_RESTORED') {
    store.dispatch(completeLogin());
  }
});

I have this file:

eventListeners.test.js

 it('dispatches completeLogin when OAUTH_SESSION_RESTORED received', () => {
    // 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
  });

However I don't succeed to test that the dispatch method of the store is called.

What I have tried so far:

1) trying to mock directly the method dispatch of the store (eg. doing jest.spyOn(store, 'dispatch') , jest.mock('@/store')).

However nothing seems to work. I think it is because the store used in eventListeners.js is not the one in the specs. So, mocking it does not do anything

2) Using the redux-mock-store library, as described in https://redux.js.org/recipes/writing-tests .

Doing

const store = mockStore({})
chrome.runtime.sendMessage({ type: 'OAUTH_SESSION_RESTORED' });
expect(store.getActions()).toEqual([{ type: 'LOGIN_COMPLETE' }])

However, same issue (I guess): the store used in the spec is not the same as in the eventListeners.js . store.getActions() returns [].

Is there a good way to test that store.dispatch get called?

===================================

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 https://github.com/reduxjs/redux/issues/546

it('dispatches completeLogin when OAUTH_SESSION_RESTORED received', () => {
    const storeChangedCallback = jest.fn()
    store.subscribe(storeChangedCallback)
    chrome.runtime.sendMessage({ type: 'OAUTH_SESSION_RESTORED' });
    expect(storeChangedCallback).toHaveBeenCalled();
    })

Is there a better way? Did I missed something?

Thank you for your answers.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • 1
    I would like to know as well. If you mock dispatch then no matter what action is dispatches it will have been called with a `[Function anonymous]` – Paul Brittain Oct 12 '18 at 14:03

0 Answers0