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

好久不见. 提交于 2019-11-29 16:00:46

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/38264715/how-to-pass-context-down-to-the-enzyme-mount-method-to-test-component-which-incl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!