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

Eri*_*ika 30 material-ui enzyme

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

TypeError: Cannot read property 'prepareStyles' of undefined

经过一番挖掘,我确实发现主题需要在上下文中传递下来.我在测试中这样做但仍然得到这个错误.

我的测试:

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

我的搜索栏组件是一个无状态组件,因此我没有涉及任何上下文.但即使我在,我仍然得到同样的错误.

我究竟做错了什么?

Níc*_*sen 49

尝试添加childContextTypesmount选项:

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

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

  • 同样适用于`shallow`,只需用浅层替换mount. (3认同)