// src
const Component = () => (
<ThemeConsumer>
{({color}) => <Text style={{color}}>Enzyme</Text>}
</ThemeConsumer>
);
test('Should find the Text component', () => {
const wrapper = shallow(
<ThemeProvider value={{color: 'yellow'}}>
<Component />
</ThemeProvider>
); // Throws an error color of undefined. (ThemeConsumer doesn't have the value passed down)
expect(wrapper.find('Component').dive().find('Text').length).toEqual(1) // Is 0
});
The shallow throws an error that the children as a function doesn't contain the theme value. (color of undefined)
Can't find the Text component
| library | version
| ----------- | -------
| Enzyme | 3.3.0
| React | 16.3.1
I fixed it this way:
ThemeContext.js
jest.mock('../src/Component', () => {
const ThemeProvider = require.requireActual('../src/Component').ThemeProvider;
const theme = require.requireActual('../src/theme');
return {
ThemeProvider,
ThemeConsumer: (props) => props.children({theme})
}
});
test('Should find the Text component', () => {
const wrapper = shallow(<Component />);
expect(wrapper.find('ThemeConsumer').dive().find('Text').length).toEqual(1)
});
hi,
Adding more information.
to find the provider you can add on attribute and the find by attribute:
...
<ThemeProvider themeprovider value={...}>
...
wrapper.find('[themeprovider]')
Most helpful comment
I fixed it this way:
__mocks__
ThemeContext.js
Test