Skip to content

Instantly share code, notes, and snippets.

@ivanbanov
Last active January 9, 2019 09:16
Show Gist options
  • Save ivanbanov/a368a0ce819535a78e6710d7657551fe to your computer and use it in GitHub Desktop.
Save ivanbanov/a368a0ce819535a78e6710d7657551fe to your computer and use it in GitHub Desktop.
Mock React context
import React from 'react';
import {storiesOf} from '@kadira/storybook';
import mockContext from '<path-to>/js/mocks/context';
import {Component} from '../';
const context = {
user: 'Foo Bar'
};
storiesOf('Component', module)
.add('default', () => {
const Component = mockContext(Component, context);
return <Component />;
});
import React, {PropTypes} from 'react';
export default function mockContext(Component: any, contextObj: Object): MockContext {
class MockContext extends React.Component {
static displayName = 'MockContext';
static childContextTypes = {};
getChildContext () {
return contextObj;
}
render () {
return <Component {...this.props} />;
}
}
for (let propertyName in contextObj) {
if (propertyName) {
MockContext.childContextTypes[propertyName] = PropTypes.any;
}
}
return MockContext;
}
import React from 'react';
import mockContext from '../context';
import {shallow} from 'enzyme';
describe('ContextHOC', () => {
beforeEach(() => {
jest.resetModules();
});
it('should get a component with the passed context props', () => {
const contextObj = {
foo: true,
bar: false
};
const Context = mockContext('div', contextObj);
const Component = shallow(<Context />);
expect(Context.childContextTypes.foo).not.toBeUndefined();
expect(Context.childContextTypes.bar).not.toBeUndefined();
expect(new Context({contextObj}).getChildContext()).toEqual(contextObj);
expect(Component.find('div').length).toBe(1);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment