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

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

我正在尝试使用 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);
  });
});

我的搜索栏组件是一个无状态组件,所以我没有在任何上下文中拉取。但即使我在,我仍然会遇到同样的错误。

我做错了什么?

尝试在 mount 选项中添加 childContextTypes

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

通过这样做,您设置了 Enzyme 包装器以使其子级通过上下文可以使用 muiTheme

这是我用 shallow 和 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'} />);