Skip to content

Instantly share code, notes, and snippets.

@sibelius
Forked from ivanbanov/component.storybook.js
Created May 24, 2017 20:29
Show Gist options
  • Save sibelius/720b5c9573fc833bccfcf28eda10ce9d to your computer and use it in GitHub Desktop.
Save sibelius/720b5c9573fc833bccfcf28eda10ce9d 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