-
-
Save sibelius/720b5c9573fc833bccfcf28eda10ce9d to your computer and use it in GitHub Desktop.
Mock React context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 />; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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