Enzyme: Shallow with New React Context API. Consumer not getting context

Created on 30 Apr 2018  路  2Comments  路  Source: enzymejs/enzyme

Expected behavior

// 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
  });

Errors

  • 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

API

  • [x] shallow
  • [ ] mount
  • [ ] render

Version

| library | version
| ----------- | -------
| Enzyme | 3.3.0
| React | 16.3.1

Adapter

  • [x] enzyme-adapter-react-16

Most helpful comment

I fixed it this way:

__mocks__

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

test('Should find the Text component', () => {
    const wrapper = shallow(<Component />); 

     expect(wrapper.find('ThemeConsumer').dive().find('Text').length).toEqual(1)
  });

All 2 comments

I fixed it this way:

__mocks__

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

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]')
Was this page helpful?
0 / 5 - 0 ratings

Related issues

andrewhl picture andrewhl  路  3Comments

AdamYahid picture AdamYahid  路  3Comments

blainekasten picture blainekasten  路  3Comments

mattkauffman23 picture mattkauffman23  路  3Comments

benadamstyles picture benadamstyles  路  3Comments