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

Erika picture Erika · Jul 8, 2016 · Viewed 18k times · Source

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?

Answer

N&#237;colas Iensen picture Nícolas Iensen · Jul 10, 2016

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.