Redux How to update the store in unit tests?

亡梦爱人 提交于 2019-12-05 02:22:10
Lucas

configureMockStore is a factory, that is used to configure mock store by applying the middlewares. returns mockStore object.
mockStore returns an instance of configured mock store. It doesn't change state through action. It just records with actions were passed. The reason behind is because it's an utility tool to create unit tests, not "integration" (state + component) tests.

Nonetheless you can simulate a state change. mockStore accepts a function, so you could do the following:

import configureMockStore from 'redux-mock-store';

const middlewares = [];
const mockStore = configureMockStore(middlewares);

let state = {
  players: {
    'audio-player-1': { paused: false }
  }
};

const store = mockStore(() => state);

Then in your tests, you can do:

state = NEW_STATE;

// now you need to make the components update the state.
// so you can dispatch any action so the mock store will notify the subscribers
store.dispatch({ type: 'ANY_ACTION' }); 

What you can do is use a real store in your test. First, create a reducer function:

const reducer = (state, action) => {
  if (action.type === actionTypes.player.UPDATE_OPTION) {
    return {
      ...state,
      players: {
        ...state.players,
        [action.id]: {
          ...state.players[action.id],
          [action.key]: action.value,
        },
      },
    };
  }
  return state;
};

(Note, if you're ok with not preserving other state in this test you could simplify the above and just return a new state.)

Then create a store with that reducer and the initial state:

import { createStore } from 'redux';

const store = createStore(reducer, {
  players: {
    'audio-player-1': { paused: false }
  }
});

With that, your dispatch with updateOption should result in the new state.

It seems now that thanks to a pr by @catarinasoliveira that you can provide your real reducer which will update the store accordingly. It's in master but I don't know if it's in npm yet, or frankly if it does what I just said, but I'm about to try it out and will report back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!