【发布时间】:2017-05-29 06:20:17
【问题描述】:
使用酶、摩卡和期望断言。
我的单元测试的目的是检查在 mergeProps 中暂停和未暂停时,调度是否使用正确的参数调用。
我需要动态更改商店的状态: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);
connectWithId:
//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,
}),
【问题讨论】:
-
是的,我还建议阅读上述文档。你应该分别测试三个不同的东西:actions、reducers、components。在测试动作(实际上是动作创建者)时,您只想确保调度的实际动作正确形成。在测试 reducer 时,您希望像您已经在做的那样模拟 store,调度一些操作,并确保返回的新状态是您所期望的。在测试组件时,您希望实际测试行为(即,如果我单击此处,则调用 dispatch),当然要模拟 dispatch。
标签: unit-testing reactjs redux mocha.js enzyme