Skip to content

Instantly share code, notes, and snippets.

@ivanbanov
Created May 24, 2017 21:11
Show Gist options
  • Save ivanbanov/2bb940f410e3111ff4921e0aeba956d2 to your computer and use it in GitHub Desktop.
Save ivanbanov/2bb940f410e3111ff4921e0aeba956d2 to your computer and use it in GitHub Desktop.
Mock Redux
import React from 'react';
import {storiesOf} from '@kadira/storybook';
import mockRedux from '<path-to>/js/mocks/redux';
import {Component} from '../';
const storeState = {
list: ['foo', 'bar', 'baz'],
someData: {
foo: true,
bar: false
}
};
storiesOf('Component', module)
.add('default', () => {
const Component = mockRedux(Component, storeState);
return <Component />;
});
import React from 'react';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware, combineReducers, compose} from 'redux';
import type {Store} from 'redux';
import thunkMiddleware from 'redux-thunk';
export default function mockRedux(Component: any, storeState: Object = {}): MockRedux {
const reducers: Object = Object
.keys(storeState)
.reduce((obj: Object, reducer: string): Object => {
obj[reducer]: Function = (state: Object = {}) => state;
return obj;
}, {});
const store: Store = createStore(
combineReducers({
...reducers
}),
storeState,
compose(
applyMiddleware(thunkMiddleware),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
return class MockRedux extends React.Component {
static displayName = 'MockRedux';
render () {
return (
<Provider store={store}>
<Component {...this.props} />
</Provider>
);
}
};
}
import React from 'react';
import mockRedux from '../redux';
import {connect, Provider} from 'react-redux';
import {shallow} from 'enzyme';
describe('ReduxHOC', () => {
beforeEach(() => {
jest.resetModules();
});
it('should get a component wrapped by a redux Provider', () => {
const storeState = {
foo: true,
bar: false
};
const Div = () => (<div>test</div>);
const ReduxComponent = mockRedux(connect()(Div), storeState);
const Component = shallow(<ReduxComponent />);
expect(Component.is(Provider)).toBe(true);
expect(Component.prop('store').getState()).toEqual({
foo: true,
bar: false
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment