35

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

TypeError: Cannot read property 'prepareStyles' of undefined

经过一番挖掘,我确实发现需要在 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);
  });
});

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

我究竟做错了什么?

4

2 回答 2

54

尝试添加选项childContextTypesmount

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

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

于 2016-07-10T18:51:41.497 回答
2

这是我用浅和挂载测试 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'} />);

于 2018-04-19T16:16:32.523 回答