【问题标题】:Unable to set context when rendering child components渲染子组件时无法设置上下文
【发布时间】:2017-02-16 15:19:57
【问题描述】:

我正在尝试使用 Enzyme 测试自定义 Material-ui React 组件,但出现以下错误:

ERROR: 'Warning: Failed context type: Required context 'muiTheme' was not specified in 'ChildComponent'.

我尝试的是根据this 设置上下文。我要访问和测试的组件是子组件。

const root = shallow(<RootComponent />, {context: {muiTheme}, childContextTypes: {muiTheme: React.PropTypes.object}})
const child = root.find(ChildComponent)
child.render() // <--- this line is throwing the error

更新:this is related

【问题讨论】:

    标签: javascript unit-testing reactjs enzyme


    【解决方案1】:

    我不确定这是否是解决方案,但它离目标更近了一步。

    const root = mount(<RootComponent />, {
      context: {muiTheme},
      childContextTypes: {muiTheme: React.PropTypes.object}
    })
    const child = root.find(ChildComponent)
    

    注意,我使用mount 而不是shallow。问题在于我不能再使用child.find({prop: 'value'}) - 返回 0 个项目...

    【讨论】:

    • 这是基于道具选择的解决方法:const findChildComponent = propValue =&gt; root.findWhere(node =&gt; node.type() === ChildComponent &amp;&amp; node.props().propName === propValue) - 显然 propName 必须替换为实际道具
    【解决方案2】:

    您需要提供&lt;muiThemeProvider&gt; 组件。

    这是一个如何做的例子:

    import React from 'react';
    import { mount } from 'enzyme';
    import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
    import Input from './Input';
    
    describe('<Input />', () => {
        const mountWithTheme = (node) => mount(<MuiThemeProvider>{node}</MuiThemeProvider>);
    
        it('calls componentDidMount', () => {
            sinon.spy(Input.prototype, 'componentDidMount');
            mountWithTheme(<Input />);
            expect(Input.prototype.componentDidMount.calledOnce).to.equal(true);
        });
    });
    

    【讨论】:

    • 我也试过这个。不走运:1)渲染整个东西并由于一些无效的 DOM 事物而引发错误(现在不记得了)2)没有解决原始问题
    • 这段代码对我有用。你的&lt;RootComponent /&gt;是什么@
    • 抽屉>菜单>菜单项。在 MenuItem 上,我有这个参数:onTouchTap。当使用mount() 时,我得到这个:错误:'警告:未知道具onTouchTap
      标签。从元素中移除这个道具。详见.... in div(由 Overlay 创建) in Overlay(由 Drawer 创建) in div(由 Drawer 创建) in Drawer(由 SideBar 创建) in SideBar(由 Unknown 创建) in Unknown'
    • import injectTapEventPlugin from 'react-tap-event-plugin'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin();
    • 哇,有道理!但是没有办法用shallow()进行测试?
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签