如何将上下文传递给Enzyme mount方法来测试包含Material UI组件的组件?

时间:2016-07-08 10:44:16

标签: material-ui enzyme

我正在尝试使用Enzyme中的mount来测试我的组件,其中嵌套了几个Material UI组件。运行测试时出现此错误:

TypeError: Cannot read property 'prepareStyles' of undefined

经过一番挖掘,I did found that a theme needs to be passed down in a context。我在测试中这样做但仍然得到这个错误。

我的测试:

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

我的搜索栏组件是一个无状态组件,因此我不会介入任何上下文。但即使我在,我仍然得到同样的错误。

我做错了什么?

2 个答案:

答案 0 :(得分:48)

尝试在childContextTypes选项中添加mount

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

通过这样做,您可以设置Enzyme包装器,以便通过上下文使muiTheme可供其子项使用。

答案 1 :(得分:2)

这是我使用浅和mount

测试Material UI的方便方法

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