Material ui 如何将上下文传递给酵素装载方法,以测试包含材质UI组件的组件?

Material ui 如何将上下文传递给酵素装载方法,以测试包含材质UI组件的组件?,material-ui,enzyme,Material Ui,Enzyme,我试图使用Enzyme的mount来测试我的组件,其中嵌套了多个材质的UI组件。我在运行测试时遇到此错误: TypeError:无法读取未定义的属性“prepareStyles” 经过一些挖掘。我在测试中这样做了,但仍然得到这个错误 我的测试: import expect from 'expect'; import React, {PropTypes} from 'react'; import {mount} from 'enzyme'; import SearchBar from './Se

我试图使用Enzyme的
mount
来测试我的组件,其中嵌套了多个材质的UI组件。我在运行测试时遇到此错误:

TypeError:无法读取未定义的属性“prepareStyles”

经过一些挖掘。我在测试中这样做了,但仍然得到这个错误

我的测试:

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);
  });
});
从“expect”导入expect;
从“React”导入React,{PropTypes};
从“酶”导入{mount};
从“./SearchBar”导入搜索栏;
从“材质ui/styles/GetMuiteme”导入GetMuiteme;
函数设置(){
常量muiTheme=getMuiTheme();
常量道具={
关闭搜索栏:()=>{},
fetchSearchData:()=>{},
数据:[],
搜索:false
};
返回挂载(,{context:{muiTheme}});
}
描述('搜索栏组件',()=>{
它('正确呈现搜索工具栏',()=>{
const wrapper=setup();
expect(wrapper.find('.toolbar').length).toBe(1);
expect(wrapper.find('button').length).toBe(1);
});
});
我的searchbar组件是一个无状态组件,所以我不在任何上下文中使用。但即使是这样,我仍然会犯同样的错误


我做错了什么?

尝试在
mount
选项中添加
childContextTypes

return mount(
  <SearchBar {...props} />, {
    context: {muiTheme},
    childContextTypes: {muiTheme: React.PropTypes.object}
  }
);
返回装载(
, {
上下文:{muiTheme},
childContextTypes:{muiTheme:React.PropTypes.object}
}
);

通过这样做,您可以设置酶包装器,使
muiTheme
在上下文中可供其孩子使用。

这是我使用shallow和mount测试材质UI的简便方法

。。。
从“材质ui/样式/MuiThemeProvider”导入MuiThemeProvider
从“材质ui/styles/GetMuiteme”导入GetMuiteme;
常量muiTheme=getMuiTheme();
const shallowWithContext=(node)=>shallow(node,{context:{muiTheme},childContextTypes:{muiTheme:PropTypes.object});
常量mountWithContext=(节点)=>mount(
节点,{context:{muiTheme},childContextTypes:{muiTheme:PropTypes.object}
);
//现在你可以做了

const wrapper=shallowWithContext('test'}/>)是的,这正是它所缺少的。我想我必须在尝试传递
contextTypes:{muiTheme:React.PropTypes.object}
时多查找一下React上下文,而不是
childContextTypes
。谢谢你,尼古拉斯!同样适用于
浅层
,只需将挂载替换为浅层即可。非常感谢!我不敢相信事情竟那么简单。我已经接受了这样一个观点:我需要始终在redux商店提供者中包装我的测试组件。shallow只适用于一个级别,这就是它的要点。酶公司的乔丹·哈班德指出了这一点。你可以在github上检查这个和这个。