Hi Guys,
I've a bit of a situation, when using enzyme for rendering React Components for my unit tests, I cannot pass over the context when I am exporting the component using react-redux's connect.
Let me show you what I mean:
Component:
class TestPage extends Component {
contextType = {
a: required
}
render() {
return (<div>1</div>);
}
}
export default TestPage;
Test:
import { shallow } from 'enzyme';
wrapper = shallow(<TestPage>, {
context: {
a: 10
}
});
This WORKS!
BUT:
Component:
class TestPage extends Component {
contextType = {
a: required
}
render() {
return (<div>1</div>);
}
}
export default connect( state => ({ a: state.runtime.a }))(TestPage);
Test:
import { shallow } from 'enzyme';
wrapper = shallow(<TestPage>, {
context: {
a: 10
}
});
Spits out: Warning: Failed Context Types: Required contextawas not specified inTestPage``
Help... How do I pass on my context through Redux's connect function?
@5punk it's the same as my issue https://github.com/airbnb/enzyme/issues/435
@MQuy can you try defining a childContextTypes as well? It should work then. I use redux-mock-store and enzyme at work and this works fine.
wrapper = shallow(<TestPage>, {
context: {
store: mockStore
},
childContextTypes: {
store: React.PropTypes.Object
}
@Aweary I tried, it's still the same, just tested in this repo https://github.com/MQuy/redux-store-enzyme
@MQuy this is exactly what we do internally where I work, so I'll have to try and reproduce when I'm back home to see what's going on 馃憤
thank @Aweary 馃憤
Does rewiring react-redux's connect function make sense?
I was trying to do something like..
import TestPage, { __RewireAPI__ as TestPageRewired } from '../TestPage';
// Rewire React-redux, connect API
TestPageRewired.__Rewire__('connect', (props) => {
console.log('Rewired Connect');
return {
contextTypes: [{ requiredContext: () => {} }],
...props
};
});
But this isn't working for me. Am I missing something?
closing in favor of #472
There's an npm module that makes it really easy to add redux to the react context
https://github.com/jamrizzi/redux-context-provider
https://www.npmjs.com/package/redux-context-provider
import React, { Component } from 'react';
import ReduxContextProvider from 'redux-context-provider';
import createStore from './createStore';
import actions from './actions';
import Routes from './routes';
export default class App extends Component {
render() {
return (
<ReduxContextProvider store={store} actions={actions}>
<Routes />
</ReduxContextProvider>
);
}
}
Most helpful comment
@MQuy can you try defining a
childContextTypesas well? It should work then. I useredux-mock-storeand enzyme at work and this works fine.