How to pass context down to the Enzyme mount metho

2019-02-08 00:00发布

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?

2条回答
Lonely孤独者°
2楼-- · 2019-02-08 00:17

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

查看更多
虎瘦雄心在
3楼-- · 2019-02-08 00:21

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.

查看更多
登录 后发表回答