Redux 如何在单元测试中更新商店?

IT技术 unit-testing reactjs redux mocha.js enzyme
2021-05-16 20:44:48

使用酶、摩卡和期望断言。

我的单元测试的目的是检查在 mergeProps 中暂停和未暂停时是否使用正确的参数调用 dispatch。我需要动态改变我的商店的状态做:paused: true

目前我尝试通过调度来更新暂停的值,但我认为这不正确,因为它只是一个模拟并且从未真正运行过减速器。

我正在使用包redux-mock-store

我该怎么做呢?

describe('Play Container', () => {
  const id = 'audio-player-1';

  const store = configureMockStore()({
    players: {
        'audio-player-1': { paused: false }
    }
  });
  let dispatchSpy;
  let wrapper;

  beforeEach(() => {
    dispatchSpy = expect.spyOn(store, 'dispatch');
    wrapper = shallow(
      <PlayContainer className={attributes.className}>
        {children}
      </PlayContainer>,
      { context: { id } },
      ).shallow({ context: { store } });
  });

  it('onClick toggles play if paused', () => {
    //Not Working
    store.dispatch(updateOption('paused', true, id));
    wrapper.simulate('click');
    expect(dispatchSpy).toHaveBeenCalledWith(play(id));
  });

  it('onClick toggles pause if playing', () => {
    wrapper.simulate('click');
    expect(dispatchSpy).toHaveBeenCalledWith(pause(id));
  });
});

容器:

const mapStateToProps = ({ players }, { id }) => ({
  paused: players[id].paused
});

const mergeProps = (stateProps, { dispatch }, { id }) => ({
  onClick: () => (stateProps.paused ? dispatch(play(id)) : dispatch(pause(id)))
});

export default connectWithId(mapStateToProps, null, mergeProps)(Play);

连接ID:

//getContext() is from recompose library and just injects id into props
export const connectWithId = (...args) => compose(
  getContext({ id: React.PropTypes.string }),
  connect(...args),
);

行动:

updateOption: (key, value, id) => ({
    type: actionTypes.player.UPDATE_OPTION,
    key,
    value,
    id,
}),
3个回答

configureMockStore是一个工厂,用于通过应用指定的中间件来配置模拟商店。这个工厂返回一个mockStore函数。

mockStore函数本身返回配置的模拟存储的实例。它不会通过动作改变状态;相反,它只记录通过了哪些操作。这是因为它是用于创建单元测试而不是“集成”(状态 + 组件)测试的实用工具

尽管如此,您可以模拟状态更改。mockStore接受一个函数,因此您可以执行以下操作:

import configureMockStore from 'redux-mock-store';

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

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

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

然后在您的测试中,您可以执行以下操作:

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' }); 

您可以做的是在测试中使用真实的商店。首先,创建一个reducer函数:

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;
};

(请注意,如果您可以在此测试中不保留其他状态,则可以简化上述内容并只返回一个新状态。)

然后使用该减速器和初始状态创建一个商店:

import { createStore } from 'redux';

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

有了这个,你的派遣updateOption应该会导致新的状态。

现在看来,多亏了@catarinasoliveira公关,您可以提供真正的减速器,这将相应地更新商店。它在 master 中,但我不知道它是否在 npm 中,或者坦率地说它是否符合我刚才所说的,但我将要尝试一下,并会回来报告