【问题标题】:How to pass context down to the Enzyme mount method to test component which includes Material UI component?如何将上下文传递给 Enzyme mount 方法以测试包含 Material UI 组件的组件?
【发布时间】:2016-11-10 21:47:34
【问题描述】:

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

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

我做错了什么?

【问题讨论】:

    标签: material-ui enzyme


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      尝试在mount 选项中添加childContextTypes

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

      通过这样做,您可以设置 Enzyme 包装器以通过上下文向其子级提供 muiTheme

      【讨论】:

      • 是的,这正是它所缺少的。我想我将不得不在尝试传递 contextTypes: {muiTheme: React.PropTypes.object} 而不是 childContextTypes 时更多地查看 React 上下文。谢谢尼古拉斯!
      • shallow 相同,只需将 mount 替换为 shallow。
      • 非常感谢!我不敢相信事情就这么简单。我已经接受了我需要始终将测试过的组件包装在 redux 存储提供程序中。
      • shallow 仅适用于一个级别,这就是重点。酶的 Jordan Harband 指出了这一点。你可以在 github 上查看这个issue 和这个issue
      猜你喜欢
      • 2018-11-27
      • 2020-05-10
      • 2020-01-23
      • 2018-11-24
      • 2021-01-23
      • 2021-05-30
      • 2016-10-29
      • 2021-05-19
      • 2017-07-29
      相关资源
      最近更新 更多