Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass context down to the Enzyme mount method to test component which includes Material UI component?

I am trying to use mount from Enzyme to test my component in which a several Material UI component are nested. I get this error when running the test:

TypeError: Cannot read property 'prepareStyles' of undefined

After some digging, I did found that a theme needs to be passed down in a context. I am doing that in the test but still get this error.

My test:

import expect from  'expect';
import React, {PropTypes} from 'react';
import {mount} from 'enzyme';
import SearchBar from './SearchBar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';

function setup() {
  const muiTheme = getMuiTheme();

  const props = {
    closeSearchBar: () => {},
    fetchSearchData: () => {},
    data: [],
    searching: false
  };

  return mount(<SearchBar {...props} />, {context: {muiTheme}});
}

describe('SearchBar Component', ()=> {

  it('Renders search toolbar properly', () => {
    const wrapper = setup();
    expect(wrapper.find('.toolbar').length).toBe(1);
    expect(wrapper.find('button').length).toBe(1);
  });
});

My searchbar component is a stateless component, so I am not pulling in any context. But even when I am, I still get the same error.

What am I doing wrong?

like image 378
Erika Avatar asked Jul 08 '16 10:07

Erika


2 Answers

Try adding childContextTypes in the mount options:

return mount(
  <SearchBar {...props} />, {
    context: {muiTheme},
    childContextTypes: {muiTheme: React.PropTypes.object}
  }
);

By doing it you set the Enzyme wrapper to make the muiTheme available to it's children through the context.

like image 155
Nícolas Iensen Avatar answered Oct 08 '22 18:10

Nícolas Iensen


this is my handy method to test Material UI with shallow and mount

...
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import getMuiTheme from 'material-ui/styles/getMuiTheme';

const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}, childContextTypes: {muiTheme: PropTypes.object}});

const mountWithContext = (node) => mount(
  node, {context: {muiTheme}, childContextTypes: {muiTheme: PropTypes.object}}
);


// now you can do
const wrapper = shallowWithContext(<Login auth={auth} onChange={() => 'test'} />);
like image 34
STEEL Avatar answered Oct 08 '22 19:10

STEEL